/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.ruoyi.web.controller.gateway;


import cn.hutool.core.lang.WeightRandom;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayTradeMergePrecreateRequest;
import com.alipay.api.request.AlipayTradeWapMergePayRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayTradeMergePrecreateResponse;
import com.alipay.api.response.AlipayTradeWapMergePayResponse;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.enums.AccountOpType;
import com.ruoyi.business.enums.OrderStatus;
import com.ruoyi.business.model.NewOrderReq;
import com.ruoyi.business.model.OrderResp;
import com.ruoyi.business.model.QueryOrderReq;
import com.ruoyi.business.model.UpOrderReq;
import com.ruoyi.business.response.ErrorResponseData;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.response.SuccessResponseData;
import com.ruoyi.business.service.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.GlobalConstants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServerExceptionEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 统一下单控制器
 *
 * @author allen
 * @date 2022-06-11 15:52:04
 */
@Api("统一下单")
@Controller
@RequestMapping("/api/v1/")
public class PayChargeController {

    private String PATH_PREFIX = "payment/";
    private static final Logger logger = LoggerFactory.getLogger(PayChargeController.class);

    private static Integer xsindex = 0;


    @Resource
    private ITOrderInfoService orderInfoService;
    @Resource
    private ITUserChannelService userChannelService;
    @Resource
    private ITPayChannelService payChannelService;
    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysDictDataService sysDictDataService;
    @Resource
    private ITRecipientInfoService recipientInfoService;
    @Resource
    private ITIsvInfoService itIsvInfoService;

    @Resource
    private AliZftPayToolService aliZftPayToolService;

    @Resource
    private ITAliZftMerchantInfoService aliZftMerchantInfoService;
    @Resource
    private CommonService commonService;
    @Resource
    private ITServerMerInfoService itServerMerInfoService;
    @Resource
    private ISysConfigService sysConfigService;
    @Resource
    private ITAccountInfoService accountInfoService;

    @Resource
    private ITAccountLogService accountLogService;

    @Resource
    private ITMergeOrderDetailService itMergeOrderDetailService;

    @Resource
    private ITOrderQrcodeInfoService itOrderQrcodeInfoService;

    private String aliAuthUrl = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=0X99&scope=auth_base&redirect_uri=";


    @Resource
    private IProxyAreaCodeService proxyAreaCodeService;

    private static AtomicInteger LOADBALANCE_FLAG = new AtomicInteger(0);
    private static AtomicInteger LOADBALANCE_USER_FLAG = new AtomicInteger(0);


    @ApiOperation("商户统一下单")
    @ResponseBody
    @PostMapping("charges")
    @Log(title = "商户统一下单", businessType = BusinessType.RECHARGE)
    public ResponseData charge(@ModelAttribute @Validated NewOrderReq newOrderReq, HttpServletRequest request) throws Exception {
        logger.info("newOrder>>>接口参数：{}", newOrderReq);
        SysUser sysUser = sysUserService.selectUserById(newOrderReq.getUid());
        String urlParam = getUrlParam(request, false);
        logger.info("urlParam={}   参与签名..", urlParam);
        // 计算sign,keySecret追加到参数字符串的头部后进行MD5加密大写
        String sign = MD5Util.stringMD5(urlParam + "&key=" + sysUser.getToken());
        // TODO delete
        logger.info("签名结果sign:{}，请求传来的签名：{}", sign, newOrderReq.getSign());
        // sign签名一致，并且timestamp和服务器时间相差在5分钟以内
        long serverTime = System.currentTimeMillis();
        String errorMsg = "";

        long clietTimeDiffMills = Math.abs(serverTime - Long.valueOf(newOrderReq.getTimestamp()));

//        if(clietTimeDiffMills > GlobalConstants.ALLOW_CLIENT_DIFF_MILLS_MAX){
//            return new BaseDataJson(HttpStatus.UNAUTHORIZED.value(),"签名sign验证错误，时间戳timestamp和平台时间误差最多允许5分钟");
//        }

        boolean checkSign = sign.equals(newOrderReq.getSign());

        boolean valid = checkSign;
        if (!checkSign) {
            throw new ServiceException(ServerExceptionEnum.SIGN_ERROR.getMessage());
        }
        logger.info("签名验证结果：{}，其中checkSign={}，isApp={}，env={}，服务器时间={}", valid,
                checkSign, serverTime);
        long userId = Long.valueOf(newOrderReq.getUid());
        logger.info("准备选择可用通道...");
        // 检查商户订单号是否已存在
        TOrderInfo query = new TOrderInfo();
        query.setOutTradeNo(newOrderReq.getOutTradeNo());
        query.setUserId(userId);
        List<TOrderInfo> exsitsOrderList = orderInfoService.selectTOrderInfoList(query);
        if (exsitsOrderList.size() > 0) {
            TOrderInfo exsitsOrder = exsitsOrderList.get(0);
//            throw new ServiceException(ServerExceptionEnum.MER_ORDER_EXSIT);
            if ("alipay_wl_h5".equals(newOrderReq.getChannel())) {
                logger.info("**********************************************特殊处理万丽通道...重新生成订单" + newOrderReq.getOutTradeNo());
                DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
                exsitsOrder.setOutTradeNo(newOrderReq.getOutTradeNo() + "_" + dateFormat.format(new Date()));
                exsitsOrder.setStatus(3);
                orderInfoService.updateTOrderInfo(exsitsOrder);
            } else {
                logger.info("返回已有支付链接...");
                return new SuccessResponseData(OrderResp.getOrder(exsitsOrder));
            }
        }

        TUserChannel userChannel = null;

        //
        TUserChannel qryUserChannel = new TUserChannel();
        qryUserChannel.setUserId(userId);
        qryUserChannel.setType(newOrderReq.getChannelType());
        qryUserChannel.setChannel(newOrderReq.getChannel());
        qryUserChannel.setDisabled(0);
        List<TUserChannel> userChannelList = userChannelService.selectTUserChannelListByNoAuth(qryUserChannel);
        if (userChannelList.size() == 0) {
            return new ErrorResponseData(ServerExceptionEnum.CHANNEL_ERROR.getCode(), ServerExceptionEnum.CHANNEL_ERROR.getMessage());
        }
        List<WeightRandom.WeightObj<TUserChannel>> weightList = new ArrayList<WeightRandom.WeightObj<TUserChannel>>();
        for (TUserChannel tUserChannel : userChannelList) {
            WeightRandom.WeightObj<TUserChannel> a = new WeightRandom.WeightObj<TUserChannel>(tUserChannel, tUserChannel.getRatio() == null ? 1 : tUserChannel.getRatio());
            weightList.add(a);
        }
        WeightRandom wr = RandomUtil.weightRandom(weightList);
        userChannel = (TUserChannel) wr.next();
        // 处理单笔限额
        TPayChannel payChannelParam = new TPayChannel();
        payChannelParam.setChannel(userChannel.getChannel());
        TPayChannel orderChannel = payChannelService.selectTPayChannelList(payChannelParam).get(0);
        long money = MoneyUtil.yuanToFen(newOrderReq.getMoney());

        if (orderChannel.getLimitPerMinMoney() > 0 && money <orderChannel.getLimitPerMinMoney()) {
            return new ErrorResponseData(ServerExceptionEnum.ORDER_LIMIT_MIN_MONEY.getCode(), String.format(ServerExceptionEnum.ORDER_LIMIT_MIN_MONEY.getMessage(), newOrderReq.getChannelType(),
                    MoneyUtil.fenToYuan(orderChannel.getLimitPerMinMoney().toString())));

        }

        if (orderChannel.getLimitPerMaxMoney() > 0 && money >orderChannel.getLimitPerMaxMoney()) {
            return new ErrorResponseData(ServerExceptionEnum.ORDER_LIMIT_MAX_MONEY.getCode(), String.format(ServerExceptionEnum.ORDER_LIMIT_MAX_MONEY.getMessage(), newOrderReq.getChannelType(),
                    MoneyUtil.fenToYuan(orderChannel.getLimitPerMaxMoney().toString())));
        }
        logger.info("======已选择通道：" + orderChannel.getChannel());

        /**
         * 下发收款号逻辑
         */

        List<TRecipientInfo> recipientInfoList = new ArrayList<>();
        SysUser userInfo = sysUserService.selectUserById(userId);
//        SysUser qryAgentUser = new SysUser();
//        qryAgentUser.setUserType(1);
//        qryAgentUser.setUserLevel(1);
//        qryAgentUser.setAncestors(userId+"");
        SysUser agentUser = sysUserService.selectUserById(userInfo.getAgentUid());
        //指定了收款号
        TRecipientInfo recipientInfoParam = null;
        if (newOrderReq.getRecipientId() != null) {

            TRecipientInfo RecipientInfo = recipientInfoService.selectTRecipientInfoById(newOrderReq.getRecipientId());
            // 收款号所有人账户必须非非冻结状态，且是开启接单状态
            SysUser rUser = sysUserService.selectUserById(RecipientInfo.getUserId());
            if (rUser.getStatus().equals("1")) {
                logger.info("用户：{}处于冻结状态，禁止接单！", rUser.getUserName());
                return new ErrorResponseData(ServerExceptionEnum.NO_AVAILABLE_RECIPIENT.getCode(), ServerExceptionEnum.NO_AVAILABLE_RECIPIENT.getMessage());
            }
//            if (rUser.getIsOpen() == 0) {
//                logger.info("用户：{}已关闭接单", rUser.getName());
//                throw new ServiceException(ServerExceptionEnum.NO_AVAILABLE_RECIPIENT);
//            }
            // && RecipientInfo.getChannelDisabled() == 0
            if (RecipientInfo != null) {
                recipientInfoList.add(RecipientInfo);
            }
        }
        // 未指定，则轮训
        else {
            //是否是外接通道
            if (orderChannel.getReqType() == 0) {
                TRecipientInfo queryTRecipientInfo = new TRecipientInfo();
                queryTRecipientInfo.setChannel(orderChannel.getChannel());
                queryTRecipientInfo.setChannelDisabled(0);
                recipientInfoList = recipientInfoService.selectTRecipientInfoList(queryTRecipientInfo);
            } else {
                // 如果是被代理的商户，则从一级总代理（包括总代理旗下码商）获取收款号
                if (userInfo.getAgentUid() > 0) {
                    //过滤被冻结，关闭收单，余额不足的1级总代理或码商
                    userInfo.setPayAmount(MoneyUtil.yuanToFen(newOrderReq.getMoney()));
                    List<SysUser> availableUserList = sysUserService.getAvailableUserList(userInfo);
                    if (availableUserList.size() == 0) {
                        return new ErrorResponseData(ServerExceptionEnum.NO_AVAILABLE_RECIPIENT.getCode(), ServerExceptionEnum.NO_AVAILABLE_RECIPIENT.getMessage());
                    }
                    //是否指定码商接单
                    TServerMerInfo tServerMerInfo = new TServerMerInfo();
                    tServerMerInfo.setShId(newOrderReq.getUid());
                    tServerMerInfo.setStatus(0);
                    List<TServerMerInfo> tServerMerInfoList = itServerMerInfoService.selectTServerMerInfoList(tServerMerInfo);
                    logger.info("商户{}指定码商接单数量：{}", userInfo.getUserName(), tServerMerInfoList.size());
                    List<TServerMerInfo> availableTServerMerInfoList = new ArrayList<>();
                    if (tServerMerInfoList.size() > 0) {
                        for (SysUser sysUser1 : availableUserList) {
                            for (TServerMerInfo tServerMerInfo1 : tServerMerInfoList) {
                                if (sysUser1.getUserId() == tServerMerInfo1.getUserId()) {
                                    availableTServerMerInfoList.add(tServerMerInfo1);
                                }
                            }
                        }
                        if (availableTServerMerInfoList.size() == 0) {
                            return new ErrorResponseData(ServerExceptionEnum.NO_AVAILABLE_RECIPIENT.getCode(), ServerExceptionEnum.NO_AVAILABLE_RECIPIENT.getMessage());
                        }
                    }
                    TServerMerInfo availableTServerMerInfo = null;
                /*List<UserInfo> availableUserList = userInfoService.getAvailableByMaster(userInfo.getAgentsMaster());
                if(CollectionUtils.isEmpty(availableUserList)){
                    throw new ServiceException(ServerExceptionEnum.NO_AVAILABLE_RECIPIENT);
                }
                // 轮询选择一个码商
                int uIndex = LOADBALANCE_USER_FLAG.getAndIncrement();
                if(uIndex < 0 ){
                    LOADBALANCE_FLAG.set(0);
                }
                uIndex = uIndex % availableUserList.size();
                logger.info("轮询选择码商==={}",availableUserList.get(uIndex).getLoginName());
                recipientInfoList = recipientInfoService.getAvailableList(availableUserList.get(uIndex).getId(),
                        channelType.getCode(),newOrderReq.getChannel());*/
                    if (availableTServerMerInfoList.size() > 0) {
                        Collections.shuffle(availableTServerMerInfoList);
                        availableTServerMerInfo = availableTServerMerInfoList.get(0);
                    }
                    if (orderChannel.getChannel().equalsIgnoreCase("alipay_kiss_h5")) {
                        logger.info("订单金额：{}", newOrderReq.getMoney());

                        recipientInfoList = recipientInfoService.getAvailableListByMoney(agentUser.getUserId(), availableTServerMerInfo, MoneyUtil.yuanToFen(newOrderReq.getMoney()), orderChannel.getChannel());
                    } else if (orderChannel.getChannel().equalsIgnoreCase("wechat_skd")) {
                        logger.info("订单金额：{}", newOrderReq.getMoney());
                        recipientInfoList = recipientInfoService.getAvailableListBySupportMoney(agentUser.getUserId(), availableTServerMerInfo, MoneyUtil.yuanToFen(newOrderReq.getMoney()), orderChannel.getChannel());
                    } else if (orderChannel.getChannel().equalsIgnoreCase("alipay_pbqz_h5")) {
                        recipientInfoParam = new TRecipientInfo();
                        String ip138Token = sysConfigService.selectConfigByKey("sys.bussine.ip138Token");
                        String[] adds = commonService.getAddresBy138Ip(newOrderReq.getOutBody(),ip138Token);
                        String province = adds[1];
                        String city = adds[2];
                        ProxyAreaCode proxyAreaCode = new ProxyAreaCode();
                        proxyAreaCode.setProvince(province);
                        proxyAreaCode.setCity(city);
                        List<ProxyAreaCode> proxyAreaCodeList = proxyAreaCodeService.selectProxyAreaCodeList(proxyAreaCode);
                        if(proxyAreaCodeList.size()>0){
                            proxyAreaCode = proxyAreaCodeList.get(0);
                            logger.info("设置码牌省份：{},城市：{}", proxyAreaCode.getProvince(),proxyAreaCode.getCity());
                            recipientInfoParam.setProvince(proxyAreaCode.getProvinceCode());
                            recipientInfoParam.setCity(proxyAreaCode.getCityCode());
                        }
                        recipientInfoParam.setAgentUid(agentUser.getUserId());
                        recipientInfoParam.setChannelType(newOrderReq.getChannelType());
                        recipientInfoParam.setChannel(orderChannel.getChannel());
                        recipientInfoParam.setMoney(MoneyUtil.yuanToFen(newOrderReq.getMoney()));
                        if (availableTServerMerInfo != null) {
                            recipientInfoParam.setUserId(availableTServerMerInfo.getUserId());
                        }
                        recipientInfoList = recipientInfoService.getAvailableListNew(recipientInfoParam);
                    } else if (orderChannel.getChannel().equalsIgnoreCase("wechat_hdf_h5")) {
                        recipientInfoParam = new TRecipientInfo();
                        recipientInfoParam.setAgentUid(agentUser.getUserId());
                        recipientInfoParam.setChannelType(newOrderReq.getChannelType());
                        recipientInfoParam.setChannel(orderChannel.getChannel());
                        recipientInfoParam.setMoney(MoneyUtil.yuanToFen(newOrderReq.getMoney()));
                        if (availableTServerMerInfo != null) {
                            recipientInfoParam.setUserId(availableTServerMerInfo.getUserId());
                        }
//                    recipientInfoList = recipientInfoService.getAvailableListNew(
//                            agentUser.getId(), newOrderReq.getChannelType(), newOrderReq.getChannel(), MoneyUtil.yuanToFen(newOrderReq.getMoney()));
                        recipientInfoList = recipientInfoService.getAvailableListNew(recipientInfoParam);
                    } else if (orderChannel.getChannel().equalsIgnoreCase("wechat_menggu_h5")) {//蒙古微信扫码
                        recipientInfoParam = new TRecipientInfo();
                        recipientInfoParam.setAgentUid(agentUser.getUserId());
                        recipientInfoParam.setChannelType(newOrderReq.getChannelType());
                        recipientInfoParam.setChannel(orderChannel.getChannel());
                        recipientInfoParam.setMoney(MoneyUtil.yuanToFen(newOrderReq.getMoney()));
                        recipientInfoParam.setSupportAmount(MoneyUtil.yuanToFen(newOrderReq.getMoney()));
                        if (availableTServerMerInfo != null) {
                            recipientInfoParam.setUserId(availableTServerMerInfo.getUserId());
                        }
//                    recipientInfoList = recipientInfoService.getAvailableListNew(
//                            agentUser.getId(), newOrderReq.getChannelType(), newOrderReq.getChannel(), MoneyUtil.yuanToFen(newOrderReq.getMoney()));
                        recipientInfoList = recipientInfoService.getAvailableListNew(recipientInfoParam);
                    } else if (orderChannel.getChannel().equalsIgnoreCase("alipay_xiongmao_pdd")) {//蒙古微信扫码
                        recipientInfoParam = new TRecipientInfo();
                        recipientInfoParam.setAgentUid(agentUser.getUserId());
                        recipientInfoParam.setChannelType(orderChannel.getType());
                        recipientInfoParam.setChannel(orderChannel.getChannel());
                        recipientInfoParam.setMoney(MoneyUtil.yuanToFen(newOrderReq.getMoney()));
                        recipientInfoParam.setSupportAmount(MoneyUtil.yuanToFen(newOrderReq.getMoney()));
                        if (availableTServerMerInfo != null) {
                            recipientInfoParam.setUserId(availableTServerMerInfo.getUserId());
                        }
//                    recipientInfoList = recipientInfoService.getAvailableListNew(
//                            agentUser.getId(), newOrderReq.getChannelType(), newOrderReq.getChannel(), MoneyUtil.yuanToFen(newOrderReq.getMoney()));
                        recipientInfoList = recipientInfoService.getAvailableListNew(recipientInfoParam);
                    } else {
                        recipientInfoParam = new TRecipientInfo();
                        recipientInfoParam.setAgentUid(agentUser.getUserId());
                        recipientInfoParam.setChannelType(newOrderReq.getChannelType());
                        recipientInfoParam.setChannel(orderChannel.getChannel());
                        recipientInfoParam.setMoney(MoneyUtil.yuanToFen(newOrderReq.getMoney()));
                        if (availableTServerMerInfo != null) {
                            recipientInfoParam.setUserId(availableTServerMerInfo.getUserId());
                        }
//                    recipientInfoParam.setIsGroupBy(1);
//                    List<RecipientInfo> recGroupBy = recipientInfoService.getAvailableListNew(recipientInfoParam);
//                    logger.info("查询GROUPBY码商数量" + recGroupBy.size());
////                    List<RecipientInfo> recGroupBy = recipientInfoService.getAvailableListNewGroupBy(
////                            agentUser.getId(), newOrderReq.getChannelType(), newOrderReq.getChannel(), MoneyUtil.yuanToFen(newOrderReq.getMoney()));
//                    if (recGroupBy.size() > 1) {
//                        //获取最后一个订单的归属码商
//                        TOrderInfo queryOrder = new TOrderInfo();
//                        queryOrder.setChannel(newOrderReq.getChannel());
//                        List<TOrderInfo> lastOrders = orderInfoService.queryLastOrder(queryOrder, 1);
//                        if (lastOrders.size() > 0) {
//                            long msUserId = lastOrders.get(0).getRecipientUid();
//                            logger.info("最后一条订单收款账号：{} 归属码商：{}", lastOrders.get(0).getChannelAccount(), msUserId);
//                            recipientInfoParam.setUserId(msUserId + "");
//                        }
////                        recipientInfoList = recipientInfoService.getAvailableListNew(
////                                agentUser.getId(), newOrderReq.getChannelType(), newOrderReq.getChannel(), MoneyUtil.yuanToFen(newOrderReq.getMoney()));
//                    }
//                    recipientInfoParam.setIsGroupBy(0);
                        recipientInfoList = recipientInfoService.getAvailableListNew(recipientInfoParam);
                    }// 打乱
//                Collections.shuffle(recipientInfoList);
                } else {
//                throw new ServiceException(ServerExceptionEnum.USER_FROZEN.getMessage());
                    return new ErrorResponseData(ServerExceptionEnum.USER_FROZEN.getCode(), ServerExceptionEnum.USER_FROZEN.getMessage());

                }
            }
        }
        logger.info("待轮询的收款账总数：{}", recipientInfoList.size());

        for (int i = recipientInfoList.size() - 1; i >= 0; i--) {
            logger.info("待轮询的收款账号：{}", recipientInfoList.get(i).getChannelAccount());
        }

        //获取最后一条订单收款账号
//        if(recipientInfoList.size()>1){
//
//            List<RecipientInfo> recGroupBy = recipientInfoService.getAvailableListNewGroupBy(
//                    agentUser.getId(), newOrderReq.getChannelType(), newOrderReq.getChannel(),MoneyUtil.yuanToFen(newOrderReq.getMoney()));
//            if(recGroupBy.size()>1){
//                TOrderInfo queryOrder = new TOrderInfo();
//                queryOrder.setChannel(newOrderReq.getChannel());
//                List<TOrderInfo> lastOrders = orderInfoService.queryLastOrder(queryOrder,1);
//                for(int i=recipientInfoList.size() - 1;i>=0;i--){
//                    if(lastOrders.get(0).getRecipientUid() == recipientInfoList.get(i).getUserId()){
//                        logger.info("去除最后一笔订单选择的收款账号："+ lastOrders.get(0).getRecipientUid());
//                        recipientInfoList.remove(i);
//                    }
//                }
//            }
//        }
        //如果有指定渠道编码，那就需要过滤
        for (int i = recipientInfoList.size() - 1; i >= 0; i--) {
            if (recipientInfoList.get(i).getChannel() != null && !orderChannel.getChannel().equals(recipientInfoList.get(i).getChannel())) {
                recipientInfoList.remove(i);
            }
        }

        // vip过滤指定服务商户。为了方便对账最好一个收款号只服务一个商户
        if (userInfo.getAgentUid() > 0 && !CollectionUtils.isEmpty(recipientInfoList)) {
            for (int i = recipientInfoList.size() - 1; i >= 0; i--) {
                if (recipientInfoList.get(i).getServeMerId() != 0 && recipientInfoList.get(i).getServeMerId() != userId) {
                    recipientInfoList.remove(i);
                }
            }
        }
        // 只选择在线的设备(店长除外）
        for (int i = recipientInfoList.size() - 1; i >= 0; i--) {
            if (recipientInfoList.get(i).getShopManager() == 0 &&
                    recipientInfoList.get(i).getNeedOnline() == 1 &&
                    recipientInfoList.get(i).getOnline() == 0) {
                logger.info("设备不在线删除：{}", recipientInfoList.get(i).getChannelAccount());
                errorMsg = "设备不在线";
                recipientInfoList.remove(i);

            }

        }
        // 如果是店长通道，那么只选择店长收款号
//        if(channel == Channel.ALIPAY_DY || channel == Channel.WECHAT_DY){
//
//            // 只选择店长收款号 ,并且需要店员在线
//            for(int i=recipientInfoList.size() - 1;i>=0;i--){
//                if( !recipientInfoList.get(i).getShopManager()
//                        || !recipientInfoList.get(i).getShopClerkOnline()){
//                    recipientInfoList.remove(i);
//                    continue;
//                }
//
//            }
//
//        }

        // 收款金额风控过滤
        for (int i = recipientInfoList.size() - 1; i >= 0; i--) {
            long limitDayMoney = recipientInfoList.get(i).getLimitDayMoney();
            long todayMoney = recipientInfoList.get(i).getTodayMoney();
            //logger.info("设置单日限额：{},总金额：{}",limitDayMoney,todayMoney);

            if (limitDayMoney > 0
                    && limitDayMoney < (money +todayMoney)) {
                logger.info("limitDayMoney单日限额删除：{}", recipientInfoList.get(i).getChannelAccount());
                errorMsg = "收款金额风控过滤【单日限额超限】";
                recipientInfoList.remove(i);

                continue;
            }

            long limitMaxMoney = recipientInfoList.get(i).getLimitMaxMoney();
            long totalMoney = recipientInfoList.get(i).getTotalMoney();
            //logger.info("设置总限额：{},总金额：{}",limitMaxMoney ,todayMoney);

            if (limitMaxMoney > 0
                    && limitMaxMoney < (money + totalMoney)) {
                logger.info("limitMaxMoney限额删除：{}", recipientInfoList.get(i).getChannelAccount());
                errorMsg = "收款金额风控过滤【总限额超限】";
                recipientInfoList.remove(i);

                continue;
            }
            //单笔限额
            long onecePayLimit = recipientInfoList.get(i).getOnecePayLimit();
            //logger.info("设置单笔限额：{},商户请求金额：{}",onecePayLimit_,money);
            if (onecePayLimit > 0
                    && onecePayLimit  < money) {
                logger.info("onecePayLimit限额删除：{}", recipientInfoList.get(i).getChannelAccount());
                errorMsg = "收款金额风控过滤【单笔限额超限】";
                recipientInfoList.remove(i);

                continue;
            }
            //今日笔数限额
            long limitDayCount = recipientInfoList.get(i).getLimitDayCount();
            long todayCount = recipientInfoList.get(i).getTodayCount();
            if (limitDayCount > 0
                    && limitDayCount < (1 + todayCount)) {
                logger.info("limitDayCount限额删除：{}", recipientInfoList.get(i).getChannelAccount());
                errorMsg = "收款金额风控过滤【今日笔数限额超限】";
                recipientInfoList.remove(i);

                continue;
            }
        }

        //京东电费判断余额剔除
        if (orderChannel.getChannel().equals("jingdong_df_wx_h5")) {
            for (int i = recipientInfoList.size() - 1; i >= 0; i--) {
                long jdDfBlance = recipientInfoList.get(i).getJdDfBlance();
                if (jdDfBlance < 0) {
                    long jdDfBlance_ = -1 * jdDfBlance;
                    if (money < jdDfBlance_) {
                        recipientInfoList.remove(i);
                        continue;
                    }
                }
            }
        }

        // 无可用收款号抛出异常
        if (CollectionUtils.isEmpty(recipientInfoList)) {
            if (orderChannel.getChannel().equals("jingdong_df_wx_h5")) {
                return new ErrorResponseData(ServerExceptionEnum.NO_AVAILABLE_JD_DF_RECIPIENT.getCode(), ServerExceptionEnum.NO_AVAILABLE_JD_DF_RECIPIENT.getMessage());
            }
            if (orderChannel.getChannel().equals("alipay_payjs_h5")) {
                return new ErrorResponseData(ServerExceptionEnum.NO_AVAILABLE_JD_DF_RECIPIENT.getCode(), ServerExceptionEnum.NO_AVAILABLE_JD_DF_RECIPIENT.getMessage());
            }
            return new ErrorResponseData(ServerExceptionEnum.NO_AVAILABLE_RECIPIENT.getCode(), ServerExceptionEnum.NO_AVAILABLE_RECIPIENT.getMessage()+"，原因："+errorMsg );
        }

        // TODO 设计更灵活的loadbalance。暂时采用随机
        /*int index = Math.abs(ThreadLocalRandom.current().nextInt());
        index = index % recipientInfoList.size();*/

        // 轮训
//        int index = LOADBALANCE_FLAG.getAndIncrement();
//        if(index < 0 ){
//            LOADBALANCE_FLAG.set(0);
//        }
//        index = index % recipientInfoList.size();
//
//        RecipientInfo recipientInfo = recipientInfoList.get(index);

        /**List<WeightRandom.WeightObj<RecipientInfo>> weightList = new ArrayList<WeightRandom.WeightObj<RecipientInfo>>();
         for (RecipientInfo recipientInfo1 : recipientInfoList) {
         WeightRandom.WeightObj<RecipientInfo> a = new WeightRandom.WeightObj<RecipientInfo>(recipientInfo1, 1);
         weightList.add(a);
         }
         WeightRandom wr = RandomUtil.weightRandom(weightList);
         RecipientInfo recipientInfo = (RecipientInfo) wr.next();**/
        Collections.shuffle(recipientInfoList);
        TRecipientInfo recipientInfo = chooseXsOne(recipientInfoList);
        logger.info("==========已成功分配收款号：" + recipientInfo.getId() + ",账号：" + recipientInfo.getChannelAccount());
        if (orderChannel.getReqType() == 1) {//包装通道
            qryUserChannel = new TUserChannel();
            qryUserChannel.setUserId(recipientInfo.getUserId());
            qryUserChannel.setChannel(orderChannel.getChannel());
            qryUserChannel.setDisabled(0);
            userChannelList = userChannelService.selectTUserChannelListByNoAuth(qryUserChannel);
            // 检查通道
            if (userChannelList.size() == 0) {
                logger.info("==========未给码商：" + recipientInfo.getUserId() + "添加" + orderChannel.getChannel() + "通道！");
                return new ErrorResponseData(ServerExceptionEnum.CHANNEL_ERROR.getCode(), ServerExceptionEnum.CHANNEL_ERROR.getMessage()+"原因：未给码商：" + recipientInfo.getUserId() + "添加" + orderChannel.getChannel() + "通道！");
            }
            //判断连续几单未成功
            Integer limitErrorCount = orderChannel.getLimitErrorCount();
            logger.info("设置连续未成功下线单数：{}", limitErrorCount);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (limitErrorCount!=null && limitErrorCount > 0 && sysUser.getIsTest()!=1) {
                TOrderInfo qryOrderInfo = new TOrderInfo();
                qryOrderInfo.setRecipientId(recipientInfo.getId());
                Map<String, Object> map = new HashMap<>();
                map.put("beginCreateTime", sdf.format(new Date()));
                qryOrderInfo.setParams(map);
                qryOrderInfo.setPaySucc(1);
                List<TOrderInfo> orderInfoList = orderInfoService.selectTOrderInfoListByNoAuth(qryOrderInfo);
                if (orderInfoList.size() == 0) {
                    qryOrderInfo.setPaySucc(0);
                    orderInfoList = orderInfoService.selectTOrderInfoListByNoAuth(qryOrderInfo);
                    logger.info("连续未成功单数：{}", orderInfoList.size());
                    if (orderInfoList.size() >= limitErrorCount) {
                        recipientInfo.setAvailable(0);
                        recipientInfoService.updateTRecipientInfo(recipientInfo);
                    }
                }
            }
        }
        // 设置收款号信息
        newOrderReq.setChannelType(recipientInfo.getChannelType());
        newOrderReq.setChannelAccount(recipientInfo.getChannelAccount());
        newOrderReq.setRecipientId(recipientInfo.getId());
        newOrderReq.setRecipientUserId(recipientInfo.getUserId());
        newOrderReq.setPlatformIs(recipientInfo.getPlatformIs());
        newOrderReq.setReceiptQrcode(recipientInfo.getReceiptQrcode());
        // 设置店员账号。如果不是店长账号，则店员账号就是本身
        newOrderReq.setClerkAccount(recipientInfo.getChannelAccount());
        newOrderReq.setCardId(recipientInfo.getCardId());
        newOrderReq.setAlipayCardid(recipientInfo.getAlipayCardid());
        if (recipientInfo.getShopManager() == 1) {
            newOrderReq.setClerkAccount(recipientInfo.getShopClerkAccount());
        }
        TOrderInfo orderInfo = new TOrderInfo();
        // 生成订单id
//        orderInfo.setId(RandomUtil.randomLong(20));
        orderInfo.setUserId(userId);
        orderInfo.setChannel(orderChannel.getChannel());
        orderInfo.setCreateTime(new Date());
        orderInfo.setNotifyUrl(newOrderReq.getNotifyUrl());
        orderInfo.setReturnUrl(newOrderReq.getReturnUrl());

        // 设置收款号信息
        orderInfo.setRecipientId(newOrderReq.getRecipientId());
        orderInfo.setRecipientUid(newOrderReq.getRecipientUserId());
        orderInfo.setChannelType(newOrderReq.getChannelType());
        orderInfo.setChannelAccount(newOrderReq.getChannelAccount());

        orderInfo.setSettleType(userInfo.getSettleType());

        orderInfo.setGoodsName(newOrderReq.getGoodsName());
        orderInfo.setOutTradeNo(newOrderReq.getOutTradeNo());
        orderInfo.setOutUserId(newOrderReq.getOutUserId());
        orderInfo.setOutBody(newOrderReq.getOutBody());
        // 设置订单请求的ip
        orderInfo.setOrderIp(IpUtils.getIpAddr(request));

        orderInfo.setCustomOrderNo(newOrderReq.getCustomOrderNo());
        // 无备注模式 需要获取可用金额
        orderInfo.setMoney(MoneyUtil.yuanToFen(newOrderReq.getMoney()));
        orderInfo.setRealMoney(orderInfo.getMoney());
        orderInfo.setLatitude(newOrderReq.getLatitude());
        orderInfo.setLongitude(newOrderReq.getLongitude());

        orderInfo.setAliAuthCode(newOrderReq.getAliAuthCode());
        orderInfo.setAliUserId(newOrderReq.getAliUserId());
        orderInfo.setChannelRate(userChannel.getUserRate());
//        orderInfo.setReceiptMoney(orderInfo.getRealMoney()*(10000-userChannel.getUserRate())/10000);
        Instant nowTime = Instant.now();
        Instant validTime = nowTime.plusSeconds(600);
        orderInfo.setValidTime(Date.from(validTime));
        if (orderChannel.getFd100() == 1) {//需要做金额浮动
            orderInfo.setStatus(1);//金额浮动设置订单状态为待支付
            logger.info("金额浮动前的订单金额：" + orderInfo.getRealMoney());
            orderInfo = getMoneyAvailable(orderInfo);
            logger.info("金额浮动后的订单金额：" + orderInfo.getRealMoney());
            if (orderChannel.getChannel().equals("card_to_card")) {
                validTime = nowTime.plusSeconds(600);
            }
            orderInfo.setValidTime(Date.from(validTime));
        }
        if (orderChannel.getChannel().equalsIgnoreCase("alipay_cez_h5")) {
            validTime = nowTime.plusSeconds(600);
            orderInfo.setValidTime(Date.from(validTime));
        }
        orderInfoService.insertTOrderInfo(orderInfo);
        // 发起付款订单
        ResponseData addOrderRes = orderInfoService.addNewOrder(orderInfo);
        if (!addOrderRes.getSuccess()) {
            return addOrderRes;
        }
        if (orderChannel.getReqType() == 1 && sysUser.getIsTest()!=1) {
            //预扣账户余额
            TAccountInfo tAccountInfo = accountInfoService.selectTAccountInfoByUserId(recipientInfo.getUserId());
            long oldbalance = tAccountInfo.getBalance();
            tAccountInfo.setBalance(tAccountInfo.getBalance() - orderInfo.getMoney());
            accountInfoService.updateTAccountInfo(tAccountInfo);
            //添加账变记录
            TAccountLog accountLog = new TAccountLog();
            accountLog.setAccountId(tAccountInfo.getId());
            accountLog.setUserId(tAccountInfo.getUserId());
            accountLog.setBizId(orderInfo.getId());
            accountLog.setOpType(AccountOpType.FROZEN_ORDER.getVal());
            accountLog.setOpDesc(String.format(AccountOpType.FROZEN_ORDER.getDesc() + "关联订单号【%d】成功扣除余额%s元", accountLog.getBizId(),
                    MoneyUtil.fenToYuan(String.valueOf(orderInfo.getMoney()))));
            // 操作金额。单位分。正数-收入，负数-支出
            accountLog.setOpAmount(orderInfo.getMoney() * -1);
            accountLog.setOldAmount(oldbalance);
            accountLog.setNewAmount(tAccountInfo.getBalance());
            // 流水
            accountLogService.insertTAccountLog(accountLog);
        }
        logger.info("下单成功。订单号：" + orderInfo.getId());
        // 查询商户自己的指定订单
        orderInfo = orderInfoService.selectTOrderInfoById(orderInfo.getId());
        logger.info("订单详情：" + JSONObject.toJSONString(orderInfo));
        OrderResp orderResp = OrderResp.getOrder(orderInfo);
        if (orderChannel.getChannel().equals("alipay_ls_h5") || orderChannel.getChannel().equals("alipay_syb_h5")) {
            orderResp.setQrcodeUrl("");
            orderResp.setQrcodeContent("");
        }
        if (orderChannel.getChannel().equals("wechat_skd")) {
            orderResp.setQrcodeContent(orderResp.getQrcodeUrl());
        }
        return new SuccessResponseData(orderResp);

    }

    @ApiOperation("商户查单")
    @ResponseBody
    @PostMapping("query")
    @Log(title = "商户查单", businessType = BusinessType.QUERY)
    public ResponseData query(@ModelAttribute @Validated QueryOrderReq queryOrderReq, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(queryOrderReq.getOrderId()) && StringUtils.isBlank(queryOrderReq.getMerOrderNo())) {
            return new ErrorResponseData("商户订单号和系统订单必须传一个");
        }
        SysUser sysUser = sysUserService.selectUserById(queryOrderReq.getUid());
        String urlParam = getUrlParam(request, false);
        logger.info("urlParam={}   参与签名..", urlParam);
        // 计算sign,keySecret追加到参数字符串的头部后进行MD5加密大写
        String sign = MD5Util.stringMD5(urlParam + "&key=" + sysUser.getToken());
        // TODO delete
        logger.info("签名结果sign:{}，请求传来的签名：{}", sign, queryOrderReq.getSign());
        if (!sign.equals(queryOrderReq.getSign())) {
            return new ErrorResponseData("签名错误");
        }
        TOrderInfo orderInfo = null;
        if (StringUtils.isNotBlank(queryOrderReq.getMerOrderNo())) {
            TOrderInfo query = new TOrderInfo();
            query.setOutTradeNo(queryOrderReq.getMerOrderNo());
            List<TOrderInfo> orderInfoList = orderInfoService.selectTOrderInfoListByNoAuth(query);
            if (orderInfoList.size() > 0) {
                orderInfo = orderInfoList.get(0);
            } else {
                return new ErrorResponseData("未查询到订单");
            }
        } else {
            orderInfo = orderInfoService.selectTOrderInfoById(Long.valueOf(queryOrderReq.getOrderId()));
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (orderInfo != null) {
            Map<String, String> signParamMap = new HashMap<>();

            signParamMap.put("tradeNo", String.valueOf(orderInfo.getId()));
            signParamMap.put("outTradeNo", orderInfo.getOutTradeNo());
            signParamMap.put("money", MoneyUtil.fenToYuan(orderInfo.getMoney().toString()));
            signParamMap.put("realMoney", MoneyUtil.fenToYuan(orderInfo.getRealMoney().toString()));
            signParamMap.put("uid", orderInfo.getUserId().toString());
            signParamMap.put("status", orderInfo.getPaySucc() + "");
            if (orderInfo.getPaySucc() == 1) {
                signParamMap.put("payAt", sdf.format(orderInfo.getPaySuccTime()));
            }
            String token = sysUserService.selectUserById(orderInfo.getUserId()).getToken();
            String rssign = MD5Util.stringMD5(SignUtil.formatUrlMap(signParamMap, false) + "&key=" + token);
            signParamMap.put("sign", rssign);
            return new SuccessResponseData(signParamMap);
        } else {
            return new ErrorResponseData("未查询到订单");
        }
    }


    private synchronized TRecipientInfo chooseXsOne(List<TRecipientInfo> list) {
        logger.info("带轮训收款号总数：{},xsindex:{}", list.size(), xsindex);

        if (list == null || list.size() == 0) return null;
        int sum = list.size();
        int temp = xsindex % sum;
        TRecipientInfo t = list.get(temp);
        xsindex++;
        return t;
    }

    private String getUrlParam(HttpServletRequest request, boolean urlEncode) throws UnsupportedEncodingException {
        Map<String, String> paramMap = new HashMap<>();
        //paramMap.put("token" , token);
        Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String paramName = (String) enumeration.nextElement();
            // 签名参数要排除
            if ("sign".equals(paramName)) {
                continue;
            }
            String paramValue = request.getParameter(paramName);
            //形成键值对应的map
            paramMap.put(paramName, paramValue);
        }
        return SignUtil.formatUrlMap(paramMap, urlEncode);
    }

    private TOrderInfo getMoneyAvailable(TOrderInfo orderInfo) {
        //先查询库中该收款账号状态为待支付的订单
        TOrderInfo query = new TOrderInfo();
        if (ObjectUtil.isNotEmpty(orderInfo.getChannel())) {
            query.setChannel(orderInfo.getChannel());
        }
        if (ObjectUtil.isNotEmpty(orderInfo.getRecipientId())) {
            query.setRecipientId(orderInfo.getRecipientId());

        }

        if (ObjectUtil.isNotEmpty(orderInfo.getChannelAccount())) {
            query.setChannelAccount(orderInfo.getChannelAccount());

        }
        // 根据实际支付金额 查询
        if (ObjectUtil.isNotEmpty(orderInfo.getRealMoney())) {
            query.setRealMoney(orderInfo.getRealMoney());

        }

        if (ObjectUtil.isNotEmpty(orderInfo.getStatus())) {
            query.setStatus(orderInfo.getStatus());

        }
        List<TOrderInfo> exitMoneyList = orderInfoService.selectTOrderInfoList(query);
        if (exitMoneyList.size() == 0) {
            return exitMoneyList.get(0);
        } else {
//            int iRandom = (int) (1 + Math.random() * 10);
            orderInfo.setRealMoney(orderInfo.getRealMoney() - 1);
            return getMoneyAvailable(orderInfo);
        }
    }


//    @ResponseBody
//    @PostMapping("query/{tradeNo}")
//    @Log(title = "商户订单查询", businessType = BusinessType.QUERY)
//    public ResponseData getOrderById(@PathVariable String tradeNo) {
//        LambdaQueryWrapper<TOrderInfo> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.and((wrapper) -> {
//            wrapper.eq(TOrderInfo::getId, tradeNo).or().eq(TOrderInfo::getOutTradeNo, tradeNo);
//        });
//        TOrderInfo orderInfo = orderInfoService.sel(queryWrapper);
//        return new SuccessResponseData(OrderResp.getOrder(orderInfo));
//    }


    @RequestMapping(value = "alipaysybh5Pay", method = RequestMethod.GET)
    public String sybPayPage(HttpServletRequest request, HttpServletResponse response,
                             @RequestParam("p") String param,
                             Model model) throws Exception {
        logger.info("sybPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);
        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;


        if (checkOK) {
//            if(type.equalsIgnoreCase("ali")){
//
//            }else if(type.equalsIgnoreCase("wechat")){
//                String payExtInfo = orderInfo.getQrcodeUrl();
//                JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
//                model.addAttribute("payTimeStamp", payExtObj.getString("payTimeStamp"));
//                model.addAttribute("payPackage", payExtObj.getString("payPackage"));
//                model.addAttribute("paySign", payExtObj.getString("paySign"));
//                model.addAttribute("payAppId", payExtObj.getString("payAppId"));
//                model.addAttribute("paynonceStr", payExtObj.getString("paynonceStr"));
//                model.addAttribute("paySignType", payExtObj.getString("paySignType"));
//                return "wxpayByTradeInfoPay";
//
//            }
            String nginxPayGateway = sysConfigService.selectConfigByKey("sys.bussine.nginxPayGateway");
            String url = nginxPayGateway + GlobalConstants.API_BASE_URL + "common/aliPayAuth/sybPay/" + param;
            String aliUrl = "alipays://platformapi/startapp?appId=10000007&clientVersion=3.7.0.0718&qrcode=" + URLEncoder.encode(url);
            String payUrl = "https://render.alipay.com/p/s/i?scheme=" + URLEncoder.encode(aliUrl);
            String payExtInfo = orderInfo.getQrcodeTxt();
            JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
            //model.addAttribute("info", this.nginxPayGateway + GlobalConstants.PAY_BASE_URL+"syxpay/alisuccess/"+pp);
            model.addAttribute("androidUrl", aliUrl);
            model.addAttribute("payUrl", payUrl);
            return PATH_PREFIX + "openAli.html";

        }
        return view;
    }

    @RequestMapping(value = "testH5Pay", method = RequestMethod.GET)
    public String testwlH5PayPage(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam("p") String param,
                                  Model model) throws Exception {
        logger.info("sybPay p ==" + param);

        boolean checkOK = true;
        String view = "error";


        if (checkOK) {
            String nginxPayGateway = sysConfigService.selectConfigByKey("sys.bussine.nginxPayGateway");

            String url = nginxPayGateway + GlobalConstants.API_BASE_URL + "common/aliPayTestAuth/wlPay/" + param;
            String aliUrl = "alipays://platformapi/startapp?appId=20000199&url=" + URLEncoder.encode(url);
            String payUrl = "https://render.alipay.com/p/s/i?scheme=" + URLEncoder.encode(aliUrl);
            model.addAttribute("androidUrl", aliUrl);
            model.addAttribute("payUrl", payUrl);
            return PATH_PREFIX + "openAli.html";

        }
        return view;
    }


    @RequestMapping(value = "alipaylsh5Pay", method = RequestMethod.GET)
    public String fslsPayPage(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam("p") String param,
                              Model model) throws Exception {
        logger.info("fslsPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);
        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
            String payExtInfo = orderInfo.getQrcodeTxt();
            JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
            //model.addAttribute("info", this.nginxPayGateway + GlobalConstants.PAY_BASE_URL+"syxpay/alisuccess/"+pp);
            model.addAttribute("tradeNo", orderInfo.getQrcodeUrl());
//            model.addAttribute("payAmt", MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
//            model.addAttribute("CUST_ID", payExtObj.getString("CUST_ID"));
//            model.addAttribute("qrcode", payExtObj.getString("qrcode"));
//            model.addAttribute("adviseId", payExtObj.getString("adviseId"));

            return PATH_PREFIX + "alipayByLsTradeNoInfoPay.html";
        }
        return view;
    }


    @RequestMapping(value = "alipaywlh5Pay", method = RequestMethod.GET)
    public String fswlPayPage(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam("p") String param,
                              Model model) throws Exception {
        logger.info("fslsPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            //retMap.put("msg", ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());

        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账");

        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
            logger.info("支付链接：" + orderInfo.getQrcodeUrl());
            model.addAttribute("payUrl", orderInfo.getQrcodeUrl());
            return PATH_PREFIX + "openLink.html";
//            outPut(response, "<script>window.location.href=\"" + orderInfo.getQrcodeUrl() + "\"</script>");
        }
        return view;
    }

    @RequestMapping(value = "alipaydyh5Pay", method = RequestMethod.GET)
    public String fsdyPayPage(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam("p") String param,
                              Model model) throws Exception {
        logger.info("alipaydyh5Pay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            //retMap.put("msg", ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());

        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账");

        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
            logger.info("支付链接：" + orderInfo.getQrcodeUrl());
            model.addAttribute("payUrl", orderInfo.getQrcodeUrl());
            return PATH_PREFIX + "openLink.html";
//            outPut(response, "<script>window.location.href=\"" + orderInfo.getQrcodeUrl() + "\"</script>");
        }
        return view;
    }


    @RequestMapping(value = "alipayhdfh5Pay", method = RequestMethod.GET)
    public String fshdfPayPage(HttpServletRequest request, HttpServletResponse response,
                               @RequestParam("p") String param,
                               Model model) throws Exception {
        logger.info("fshdfPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
//            if(type.equalsIgnoreCase("ali")){
//
//            }else if(type.equalsIgnoreCase("wechat")){
//                String payExtInfo = orderInfo.getQrcodeUrl();
//                JSONObject payExtObj = JSONObject.parseObject(payExtInfo).getJSONObject("data");
//                logger.info("payExtObj==" + payExtObj);
//                model.addAttribute("payTimeStamp", payExtObj.getString("timeStamp"));
//                model.addAttribute("payPackage", payExtObj.getString("wxPackage"));
//                model.addAttribute("paySign", payExtObj.getString("paySign"));
//                model.addAttribute("payAppId", payExtObj.getString("appId"));
//                model.addAttribute("paynonceStr", payExtObj.getString("nonceStr"));
//                model.addAttribute("paySignType", payExtObj.getString("signType"));
//                return PATH_PREFIX+"wxpayByTradeInfoPay";
//            }
            model.addAttribute("tradeNo", orderInfo.getQrcodeUrl());
            return PATH_PREFIX + "alipayByLsTradeNoInfoPay.html";
        }
        return view;
    }


    @RequestMapping(value = "alipayyxeh5Pay", method = RequestMethod.GET)
    public String fsyxePayPage(HttpServletRequest request, HttpServletResponse response,
                               @RequestParam("p") String param,
                               Model model) throws Exception {
        logger.info("fsyxePay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
            String payExtInfo = orderInfo.getQrcodeTxt();
            JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
            JSONObject payObj = new JSONObject();
            payObj.put("totalAmount", MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
            payObj.put("methodType", "ALI_PAY");
            payObj.put("sellerId", payExtObj.getString("sellerId"));
            payObj.put("longitude", payExtObj.getString("longitude"));
            payObj.put("latitude", payExtObj.getString("latitude"));
            payObj.put("orderRemark", "");
            payObj.put("codeId", payExtObj.getString("codeId"));
            payObj.put("payModeExt", "1");
            String payInfoStr = payObj.toJSONString();
            model.addAttribute("payInfoStr", payInfoStr);
            model.addAttribute("p", param);
            logger.info("生成银小二请求参数：" + payInfoStr);
            logger.info("订单号：" + param);
            return PATH_PREFIX + "alipayByYxeTradeNoInfoPay.html";
        }
        return view;
    }

    @RequestMapping(value = "alipayefth5Pay", method = RequestMethod.GET)
    public String alipayeft5Pay(HttpServletRequest request, HttpServletResponse response,
                                @RequestParam("p") String param,
                                Model model) throws Exception {
        logger.info("alipayeft5Pay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {

            String tradeNo = orderInfo.getQrcodeUrl();
            model.addAttribute("tradeNo", tradeNo);
            logger.info("tradeNo：" + tradeNo);
            logger.info("订单号：" + param);
            return PATH_PREFIX + "alipayByTradeNoPay.html";
        }
        return view;
    }

    @RequestMapping(value = "alipaycxzfh5Pay", method = RequestMethod.GET)
    public String alipaycxzfh5Pay(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam("p") String param,
                                  Model model) throws Exception {
        logger.info("alipaycxzfh5Pay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {

            String tradeNo = orderInfo.getQrcodeUrl();
            model.addAttribute("tradeNo", tradeNo);
            logger.info("tradeNo：" + tradeNo);
            logger.info("订单号：" + param);
            return PATH_PREFIX + "alipayByTradeNoPay.html";
        }
        return view;
    }


    @RequestMapping(value = "cardtocardPay", method = RequestMethod.GET)
    public String cardtocardPayPage(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam("p") String param,
                                    Model model) throws Exception {
        logger.info("cardtocardPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
            TRecipientInfo userRecipientInfo = recipientInfoService.selectTRecipientInfoById(orderInfo.getRecipientId());
            model.addAttribute("channelAccount", userRecipientInfo.getChannelAccount());
            model.addAttribute("bankName", userRecipientInfo.getBankName().split("【")[0]);
            model.addAttribute("cardNo", userRecipientInfo.getCardNo());
            model.addAttribute("money", orderInfo.getRealMoney());
            model.addAttribute("orderNo", orderInfo.getId());

            logger.info("订单号：" + param);
            return PATH_PREFIX + "card.html";
        }
        return view;
    }

    @RequestMapping(value = "alipaysmjsmh5Pay", method = RequestMethod.GET)
    public String smjsmh5Pay(HttpServletRequest request, HttpServletResponse response,
                             @RequestParam("p") String param,
                             Model model) throws Exception {
        logger.info("fslsPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            //retMap.put("msg", ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());

        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账");

        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
            logger.info("支付链接：" + orderInfo.getQrcodeUrl());
//            String url = nginxPayGateway + GlobalConstants.API_BASE_URL + "common/aliPayTestAuth/wlPay/" + param;
//            String aliUrl = "alipays://platformapi/startapp?appId=20000199&url=" + URLEncoder.encode(url);
//            String payUrl = "https://render.alipay.com/p/s/i?scheme=" + URLEncoder.encode(aliUrl);
//            model.addAttribute("androidUrl", aliUrl);
//            model.addAttribute("payUrl", payUrl);
//            return PATH_PREFIX + "openAli.html";
            outPut(response, "<script>window.location.href=\"" + orderInfo.getQrcodeUrl() + "\"</script>");
        }
        return view;
    }


    //wechatsmjxlmh5Pay
    @RequestMapping(value = "wechatsmjxlmh5Pay", method = RequestMethod.GET)
    public String wechatsmjxlmh5Pay(HttpServletRequest request, HttpServletResponse response,
                                    @RequestParam("p") String param,
                                    Model model) throws Exception {
        logger.info("fslsPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            //retMap.put("msg", ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());

        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账");

        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
            logger.info("支付链接：" + orderInfo.getQrcodeUrl());
//            String url = nginxPayGateway + GlobalConstants.API_BASE_URL + "common/aliPayTestAuth/wlPay/" + param;
//            String aliUrl = "alipays://platformapi/startapp?appId=20000199&url=" + URLEncoder.encode(url);
//            String payUrl = "https://render.alipay.com/p/s/i?scheme=" + URLEncoder.encode(aliUrl);
            model.addAttribute("orderCode", param);
            model.addAttribute("amount", MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
            model.addAttribute("payUrl", orderInfo.getQrcodeUrl());
            return PATH_PREFIX + "wxscan.html";
//            outPut(response, "<script>window.location.href=\"" + orderInfo.getQrcodeUrl() + "\"</script>");
        }
        return view;
    }


    @RequestMapping(value = "alipaypbqzh5Pay", method = RequestMethod.GET)
    public String alipaypbqzh5Pay(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam("p") String param,
                                  Model model) throws Exception {
        logger.info("fslsPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            //retMap.put("msg", ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());

        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账");

        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
            logger.info("支付链接：" + orderInfo.getQrcodeUrl());
//            String url = nginxPayGateway + GlobalConstants.API_BASE_URL + "common/aliPayTestAuth/wlPay/" + param;
//            String aliUrl = "alipays://platformapi/startapp?appId=20000199&url=" + URLEncoder.encode(url);
//            String payUrl = "https://render.alipay.com/p/s/i?scheme=" + URLEncoder.encode(aliUrl);
//            model.addAttribute("orderCode", param);
//            model.addAttribute("amount", MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
//            model.addAttribute("payUrl", orderInfo.getQrcodeUrl());
//            return PATH_PREFIX + "wxscan.html";
            outPut(response, "<script>window.location.href=\"" + orderInfo.getQrcodeUrl() + "\"</script>");
        }
        return view;
    }

    //支付宝授权回调
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "common/aliPayAuth/{serviceName}/{orderCode}")
    public String aliPayAuth(HttpServletRequest request, @PathVariable(value = "orderCode") String orderCode, @PathVariable(value = "serviceName") String serviceName,
                             @RequestParam(value = "auth_code", required = false) String auth_code,
                             HttpServletResponse response, Model model) throws Exception {
        logger.info("接收加密后的订单号:" + orderCode);
        String content = AesEncryptUtils.decrypt(orderCode);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");
        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        if (orderInfo == null) {
            outPut(response, "aliPay获取订单失败！");
        }
        String aliUserId = "";
        String nginxPayGateway = sysConfigService.selectConfigByKey("sys.bussine.nginxPayGateway");
        String aliPrivateKey = sysConfigService.selectConfigByKey("sys.bussine.aliPrivateKey");
        String aliPublicKey = sysConfigService.selectConfigByKey("sys.bussine.aliPublicKey");
        String aliAppid = sysConfigService.selectConfigByKey("sys.bussine.aliAppid");
        if (StringUtils.isEmpty(auth_code)) {

            String result = this.aliAuthUrl.replaceAll("0X99", aliAppid) + URLEncoder.encode(nginxPayGateway + GlobalConstants.API_BASE_URL + "common/aliPayAuth/" + serviceName + "/" + orderCode);
            logger.info("获取用户ID====" + result);
            String url = "<script>window.location.href=\"" + result + "\"</script>";
            try {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().println(url);
                response.getWriter().flush();
                response.getWriter().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            logger.info("auth_code====" + auth_code);
            if (StringUtils.isEmpty(orderInfo.getAliUserId())) {
                //实例化客户端 参数：正式环境URL,Appid,商户私钥 PKCS8格式,字符编码格式,字符格式,支付宝公钥,签名方式
                AlipayClient alipayClient = null;
                if (orderInfo.getChannel().equals("alipay_syb_h5")) {
                    //根据码牌的地址获取相应的代理IP
                    TRecipientInfo userRecipientInfo = recipientInfoService.selectTRecipientInfoById(Long.valueOf(orderInfo.getRecipientId()));
                    logger.info("挂码省份：" + userRecipientInfo.getProvince());
                    logger.info("挂码城市：" + userRecipientInfo.getCity());
                    //先从数据库获取没有重新请求
                    JSONObject ipObject = commonService.getPoxyIp(orderInfo);
                    String ip = ipObject.getString("ip");
                    String port = ipObject.getString("port");
                    String proxyIp = ip + ":" + port;

                    orderInfo.setProxyIp(proxyIp);
                    alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliAppid, aliPrivateKey, "json", "GBK", aliPublicKey, "RSA2", ip, port);

                } else {
                    alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliAppid, aliPrivateKey, "json", "GBK", aliPublicKey, "RSA2");

                }

                AlipaySystemOauthTokenRequest alipaySystemOauthTokenRequest = new AlipaySystemOauthTokenRequest();
                // 值为authorization_code时，代表用code换取
                alipaySystemOauthTokenRequest.setGrantType("authorization_code");
                //授权码，用户对应用授权后得到的
                alipaySystemOauthTokenRequest.setCode(auth_code);
                //这里使用execute方法
                AlipaySystemOauthTokenResponse alipaySystemOauthTokenResponse = alipayClient.execute(alipaySystemOauthTokenRequest);
                //刷新令牌，上次换取访问令牌时得到。见出参的refresh_token字段
                alipaySystemOauthTokenRequest.setRefreshToken(alipaySystemOauthTokenResponse.getAccessToken());
                //返回成功时 就将唯一标识返回
                logger.info("返回====" + JSON.toJSONString(alipaySystemOauthTokenResponse));
                if (alipaySystemOauthTokenResponse.isSuccess()) {
                    aliUserId = alipaySystemOauthTokenResponse.getUserId();

                    if (org.apache.commons.lang3.StringUtils.isBlank(orderInfo.getAliUserId())) {
                        orderInfo.setAliUserId(aliUserId);
                        orderInfo.setAliAuthCode(auth_code);
                        orderInfoService.updateTOrderInfo(orderInfo);
                    }
                }
            }
//            String queryAliBackUrl = sysConfigService.selectConfigByKey("sys.bussine.queryAliBackUrl");
//
//            String aliBlackRs = HttpUtils.sendPostRequest(queryAliBackUrl + "/" + aliUserId, "");
//            JSONObject aliBlackObj = JSONObject.parseObject(aliBlackRs);
//            logger.info("查询专投库返回：" + aliBlackRs);
//            if (aliBlackObj.getString("isBlack").equals("true")) {
//                outPut(response, "aliObj获取订单失败！");
//            }

            if (org.apache.commons.lang3.StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                TPayChannel payChannel = payChannelService.selectTPayChannelByCode(orderInfo.getChannel());
                PaymentInterface paymentInterface;
                try {
                    paymentInterface = (PaymentInterface) SpringUtils.getBean(payChannel.getAliasName().toLowerCase() + "PayService");
                } catch (BeansException e) {
                    logger.info(e.getMessage());
                    throw new ServiceException("支付渠道类型[channel=" + payChannel.getChannel() + "]实例化异常");
                }
                JSONObject payInfo = paymentInterface.createPayOrder(orderInfo);
                if (payInfo.getString("code").equalsIgnoreCase("200")) {
                    orderInfo = orderInfoService.selectTOrderInfoById(orderId);
                    orderInfo.setPay3rdOrderNo(payInfo.getString("orderNo"));
                    orderInfo.setQrcodeUrl(payInfo.getString("payUrl"));
                    orderInfoService.updateTOrderInfo(orderInfo);
                    if (orderInfo.getChannel().equals("alipay_xyf_h5")) {
//                    JSONObject payInfo = xyfPayService.createPayOrder(orderInfo);
//                    if (payInfo.getString("code").equalsIgnoreCase("200")) {
//                        orderInfo = orderInfoService.getById(orderId);
//                        orderInfo.setPay3rdOrderNo(payInfo.getString("orderNo"));
//                        orderInfoService.update(orderInfo);
//                        String payExtInfo = orderInfo.getQrcodeTxt();
//                        JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
//                        //model.addAttribute("info", this.nginxPayGateway + GlobalConstants.PAY_BASE_URL+"syxpay/alisuccess/"+pp);
//                        model.addAttribute("tradeNo", payInfo.getString("payUrl"));
//                        model.addAttribute("payAmt", MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
//                        model.addAttribute("CUST_ID", payExtObj.getString("CUST_ID"));
//                        model.addAttribute("qrcode", payExtObj.getString("qrcode"));
//                        model.addAttribute("adviseId", payExtObj.getString("adviseId"));
//                        model.addAttribute("orderCode", pp);
//                        model.addAttribute("domain", this.nginxPayGateway);
//                        return "alipayByTradeNoInfoPay";
//                    } else {
//                        outPut(response, "通道异常,请再次重试！");
//                    }
                    } else if (orderInfo.getChannel().equals("alipay_syb_h5")) {
                        model.addAttribute("tradeNo", payInfo.getString("payUrl"));
                        return PATH_PREFIX + "alipayByTradeNoPay.html";
                    }else{
                        outPut(response, "<script>window.location.href=\"" + payInfo.getString("payUrl") + "\"</script>");
                    }

                } else {
                    outPut(response, "通道异常,请再次重试！");
                }
            } else {
//                    model.addAttribute("info", this.nginxPayGateway + GlobalConstants.PAY_BASE_URL+"syxpay/alisuccess/"+pp);
                if (orderInfo.getChannel().equals("alipay_xyf_h5")) {
                    String payExtInfo = orderInfo.getQrcodeTxt();
                    JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
                    model.addAttribute("tradeNo", orderInfo.getPay3rdOrderNo());
                    model.addAttribute("payAmt", MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                    model.addAttribute("CUST_ID", payExtObj.getString("CUST_ID"));
                    model.addAttribute("qrcode", payExtObj.getString("qrcode"));
                    model.addAttribute("adviseId", payExtObj.getString("adviseId"));
                    model.addAttribute("orderCode", content);
                    model.addAttribute("domain", nginxPayGateway);
                    return PATH_PREFIX + "alipayByTradeNoInfoPay.html";
                } else if (orderInfo.getChannel().equals("alipay_syb_h5")) {
                    model.addAttribute("tradeNo", orderInfo.getQrcodeUrl());
                    return PATH_PREFIX + "alipayByTradeNoPay.html";

                }

            }
        }
        return null;

    }

    private boolean outPut(HttpServletResponse response, String errorMsg) {
        try {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().println(errorMsg);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    @RequestMapping(value = "alipay/fsyxePay", method = RequestMethod.GET)
    public String aliPayFsyxePayPage(HttpServletRequest request, HttpServletResponse response,
                                     @RequestParam("p") String param,
                                     @RequestParam("requestData") String requestData,
                                     Model model) throws Exception {
        logger.info("加密完的数据 p ==" + param + "==========" + requestData);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());

        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");

        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());

        }
        checkOK = true;

        if (checkOK) {
            TRecipientInfo userRecipientInfo = recipientInfoService.selectTRecipientInfoById(orderInfo.getRecipientId());
//            logger.info("挂码省份：" + userRecipientInfo.getProvince());
//            logger.info("挂码城市：" + userRecipientInfo.getCity());
//            JSONObject ipObject = commonService.getPoxyIp(orderInfo);
//            String ip = ipObject.getString("ip");
//            String port = ipObject.getString("port");
            String payExtInfo = orderInfo.getQrcodeTxt();
            JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
            String url = "https://longpay.xddshare.com/ysepay/checkout/api/merchant/query";
            logger.info("银小二生成支付宝链接：" + url);
            JSONObject reqObj = new JSONObject();
            reqObj.put("requestData", requestData);
            //String payRes = HttpUtils.sendJsonMessageByProxyIp(url,new HashMap<>(),reqObj.toJSONString(),ip+":"+port);
            String payRes = HttpUtils.sendJsonMessage(url, new HashMap<>(), reqObj.toJSONString());

            logger.info("银小二生成支付宝链接返回：" + payRes);

            JSONObject payResObj = JSONObject.parseObject(payRes);

            if (payResObj.getIntValue("code") != 0) {
                userRecipientInfo.setChannelDisabled(1);
                userRecipientInfo.setOnline(0);
                userRecipientInfo.setAvailable(0);
                recipientInfoService.updateTRecipientInfo(userRecipientInfo);
                outPut(response, "YXE获取订单失败！");
            }
            JSONObject data = payResObj.getJSONObject("data");
            orderInfo.setPay3rdOrderNo(data.getString("combine_trade_no"));
            orderInfo.setPayUrl(data.getString("source_qr_code_url"));
            orderInfoService.updateTOrderInfo(orderInfo);
            model.addAttribute("payUrl", data.getString("source_qr_code_url"));
            return PATH_PREFIX + "openLink.html";
        }
        return view;
    }

    @RequestMapping(value = "alipaycezh5Pay", method = RequestMethod.GET)
    public String alipaycezh5PayPage(HttpServletRequest request, HttpServletResponse response,
                                     @RequestParam("p") String param,
                                     Model model) throws Exception {
        logger.info("cezPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;


        if (checkOK) {
//            if(type.equalsIgnoreCase("ali")){
//
//            }else if(type.equalsIgnoreCase("wechat")){
//                String payExtInfo = orderInfo.getQrcodeUrl();
//                JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
//                model.addAttribute("payTimeStamp", payExtObj.getString("payTimeStamp"));
//                model.addAttribute("payPackage", payExtObj.getString("payPackage"));
//                model.addAttribute("paySign", payExtObj.getString("paySign"));
//                model.addAttribute("payAppId", payExtObj.getString("payAppId"));
//                model.addAttribute("paynonceStr", payExtObj.getString("paynonceStr"));
//                model.addAttribute("paySignType", payExtObj.getString("paySignType"));
//                return "wxpayByTradeInfoPay";
//
//            }
            String payUrl = orderInfo.getQrcodeUrl();
            JSONObject payObj = JSONObject.parseObject(payUrl);
            model.addAttribute("payUrl", payObj.getString("payInfo"));
            return PATH_PREFIX + "alipayByTradeNoInfoPay.html";
        }
        return view;
    }

    @RequestMapping(value = "alipayapp", method = RequestMethod.GET)
    public String alipayappPayPage(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam("p") String param,
                                   Model model) throws Exception {
        logger.info("cezPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);

        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;


        if (checkOK) {
//            if(type.equalsIgnoreCase("ali")){
//
//            }else if(type.equalsIgnoreCase("wechat")){
//                String payExtInfo = orderInfo.getQrcodeUrl();
//                JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
//                model.addAttribute("payTimeStamp", payExtObj.getString("payTimeStamp"));
//                model.addAttribute("payPackage", payExtObj.getString("payPackage"));
//                model.addAttribute("paySign", payExtObj.getString("paySign"));
//                model.addAttribute("payAppId", payExtObj.getString("payAppId"));
//                model.addAttribute("paynonceStr", payExtObj.getString("paynonceStr"));
//                model.addAttribute("paySignType", payExtObj.getString("paySignType"));
//                return "wxpayByTradeInfoPay";
//
//            }
            String payUrl = orderInfo.getQrcodeUrl();
            model.addAttribute("payUrl", payUrl);
            return PATH_PREFIX + "alipayByTradeNoInfoPay.html";
        }
        return view;
    }


    @RequestMapping(value = "alipaykmth5Pay", method = RequestMethod.GET)
    public String alipaykmth5PayPage(HttpServletRequest request, HttpServletResponse response,
                                     @RequestParam("p") String param,
                                     Model model) throws Exception {
        logger.info("alipaykmth5Pay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);
        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
            String payUrl = orderInfo.getQrcodeUrl();
            if (payUrl.startsWith("alipays")) {
                model.addAttribute("payUrl", payUrl);
                logger.info("payurl：" + payUrl);
                logger.info("订单号：" + param);
                return PATH_PREFIX + "openLink.html";
            } else {
                model.addAttribute("tradeNo", payUrl);
                logger.info("payurl：" + payUrl);
                logger.info("订单号：" + param);
                return PATH_PREFIX + "alipayByTradeNoPay.html";
            }

        }
        return view;
    }

    //gfalipayddmPay

    @RequestMapping(value = "gfalipayddmPay", method = RequestMethod.GET)
    public String gfalipayddmPayPage(HttpServletRequest request, HttpServletResponse response,
                                     @RequestParam("p") String param,
                                     Model model) throws Exception {
        logger.info("alipaykmth5Pay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);
        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
            String payUrl = orderInfo.getQrcodeUrl();
            logger.info("payurl：" + payUrl);
            logger.info("订单号：" + param);
            return PATH_PREFIX + "openLink.html";

        }
        return view;
    }


    @RequestMapping(value = "wechatcezh5Pay", method = RequestMethod.GET)
    public String wechatCezH5Page(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam("p") String param,
                                  Model model) throws Exception {
        logger.info("cezPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);
        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;


        if (checkOK) {
//            if(type.equalsIgnoreCase("ali")){
//
//            }else if(type.equalsIgnoreCase("wechat")){
//                String payExtInfo = orderInfo.getQrcodeUrl();
//                JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
//                model.addAttribute("payTimeStamp", payExtObj.getString("payTimeStamp"));
//                model.addAttribute("payPackage", payExtObj.getString("payPackage"));
//                model.addAttribute("paySign", payExtObj.getString("paySign"));
//                model.addAttribute("payAppId", payExtObj.getString("payAppId"));
//                model.addAttribute("paynonceStr", payExtObj.getString("paynonceStr"));
//                model.addAttribute("paySignType", payExtObj.getString("paySignType"));
//                return "wxpayByTradeInfoPay";
//
//            }
            String payUrl = orderInfo.getQrcodeUrl();
            JSONObject payObj = JSONObject.parseObject(payUrl);
            model.addAttribute("package", payObj.getString("package"));
            model.addAttribute("appid", payObj.getString("appid"));
            model.addAttribute("sign", payObj.getString("sign"));
            model.addAttribute("partnerid", payObj.getString("partnerid"));
            model.addAttribute("prepayid", payObj.getString("prepayid"));
            model.addAttribute("noncestr", payObj.getString("noncestr"));
            model.addAttribute("timestamp", payObj.getString("timestamp"));

            return PATH_PREFIX + "wechatByPrepayidPay.html";
        }
        return view;
    }

    @RequestMapping(value = "/payment/{payMethod}", method = RequestMethod.GET)
    public String paymentPage(HttpServletRequest request, HttpServletResponse response,@PathVariable("payMethod") String payMethod,
                             @RequestParam("p") String param,
                             Model model) throws Exception {
        logger.info("sybPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);
        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;


        if (checkOK) {
            TRecipientInfo userRecipientInfo = recipientInfoService.selectTRecipientInfoById(orderInfo.getRecipientId());
            JSONObject rsCfgObj = JSONObject.parseObject(userRecipientInfo.getReturnJson());
            if(payMethod.equalsIgnoreCase("dongwo")|| payMethod.equalsIgnoreCase("zidiantong")||payMethod.equalsIgnoreCase("gfalif2f")
                || payMethod.equalsIgnoreCase("gfaliddm")||payMethod.equalsIgnoreCase("yunyinqian")
            ){
                String payUrl = orderInfo.getQrcodeUrl();
                logger.info("payurl：" + payUrl);
                String androidPayUrl = "";
                model.addAttribute("orderCode", param);
                model.addAttribute("amount", MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                model.addAttribute("payUrl", payUrl);
                model.addAttribute("androidPayUrl", payUrl);
                return PATH_PREFIX + "alipay.html";
            }else if(payMethod.equalsIgnoreCase("wxskd")){
                String payUrl = orderInfo.getQrcodeContent();
                TOrderQrcodeInfo tOrderQrcodeInfo = new TOrderQrcodeInfo();
                tOrderQrcodeInfo.setOrderId(orderInfo.getId());
                List<TOrderQrcodeInfo> list = itOrderQrcodeInfoService.selectTOrderQrcodeInfoList(tOrderQrcodeInfo);
                if (list.size() == 0) {
                    outPut(response, "未生成支付二维码");
                }
                tOrderQrcodeInfo = list.get(0);
                model.addAttribute("orderCode", param);
                model.addAttribute("amount", MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                model.addAttribute("skdImage", "data:image/png;base64," + tOrderQrcodeInfo.getQrcodeContent());
                return PATH_PREFIX + "wxskd.html";
            }else if(payMethod.equalsIgnoreCase("alipaysybh5")){
                String nginxPayGateway = sysConfigService.selectConfigByKey("sys.bussine.nginxPayGateway");
                String url = nginxPayGateway + GlobalConstants.API_BASE_URL + "common/aliPayAuth/sybPay/" + param;
                String aliUrl = "alipays://platformapi/startapp?appId=10000007&clientVersion=3.7.0.0718&qrcode=" + URLEncoder.encode(url);
                String payUrl = "https://render.alipay.com/p/s/i?scheme=" + URLEncoder.encode(aliUrl);
                String payExtInfo = orderInfo.getQrcodeTxt();
                JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
                //model.addAttribute("info", this.nginxPayGateway + GlobalConstants.PAY_BASE_URL+"syxpay/alisuccess/"+pp);
                model.addAttribute("androidUrl", aliUrl);
                model.addAttribute("payUrl", payUrl);
                return PATH_PREFIX + "openAli.html";
            }else if(payMethod.equalsIgnoreCase("common")  || payMethod.equalsIgnoreCase("game")||payMethod.equalsIgnoreCase("gfalixcx")){

                String payUrl = orderInfo.getQrcodeUrl();
                logger.info("payurl：" + payUrl);
                outPut(response, "<script>window.location.href=\"" + orderInfo.getQrcodeUrl() + "\"</script>");
            }else if(payMethod.equalsIgnoreCase("lakala")){
                String payUrl = orderInfo.getQrcodeUrl();
                logger.info("payurl：" + payUrl);
                String androidPayUrl = "";
                model.addAttribute("orderCode", param);
                model.addAttribute("amount", MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                model.addAttribute("payUrl", payUrl);
                model.addAttribute("androidPayUrl", payUrl);
                return PATH_PREFIX + "alipayScan.html";
            }else if(payMethod.equalsIgnoreCase("alipayZhzz")){
                String payUrl = orderInfo.getQrcodeUrl();
                logger.info("payurl：" + payUrl);
                String androidPayUrl =  "https://render.alipay.com/p/s/i?scheme=" + URLEncoder.encode(payUrl);
                model.addAttribute("orderCode", param);
                model.addAttribute("account", userRecipientInfo.getChannelAccount());
                model.addAttribute("name", userRecipientInfo.getRealName());
                model.addAttribute("amount", MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                model.addAttribute("payUrl", payUrl);
                model.addAttribute("androidPayUrl", androidPayUrl);
                return PATH_PREFIX + "alipayZhzz.html";
            }

        }
        return view;
    }

    @RequestMapping(value = "wechatskdscanPay", method = RequestMethod.GET)
    public String wechatskdscanPayPage(HttpServletRequest request, HttpServletResponse response,
                                       @RequestParam("p") String param,
                                       Model model) throws Exception {
        logger.info("wechatskdscanPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);
        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;


        if (checkOK) {
//            if(type.equalsIgnoreCase("ali")){
//
//            }else if(type.equalsIgnoreCase("wechat")){
//                String payExtInfo = orderInfo.getQrcodeUrl();
//                JSONObject payExtObj = JSONObject.parseObject(payExtInfo);
//                model.addAttribute("payTimeStamp", payExtObj.getString("payTimeStamp"));
//                model.addAttribute("payPackage", payExtObj.getString("payPackage"));
//                model.addAttribute("paySign", payExtObj.getString("paySign"));
//                model.addAttribute("payAppId", payExtObj.getString("payAppId"));
//                model.addAttribute("paynonceStr", payExtObj.getString("paynonceStr"));
//                model.addAttribute("paySignType", payExtObj.getString("paySignType"));
//                return "wxpayByTradeInfoPay";
//
//            }
            String payUrl = orderInfo.getQrcodeContent();
            TOrderQrcodeInfo tOrderQrcodeInfo = new TOrderQrcodeInfo();
            tOrderQrcodeInfo.setOrderId(orderInfo.getId());
            List<TOrderQrcodeInfo> list = itOrderQrcodeInfoService.selectTOrderQrcodeInfoList(tOrderQrcodeInfo);
            if (list.size() == 0) {
                outPut(response, "未生成支付二维码");
            }
            tOrderQrcodeInfo = list.get(0);
            model.addAttribute("orderCode", param);
            model.addAttribute("amount", MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
            model.addAttribute("skdImage", "data:image/png;base64," + tOrderQrcodeInfo.getQrcodeContent());
            return PATH_PREFIX + "wxskd.html";
        }
        return view;
    }

    @ResponseBody
    @RequestMapping(value = "transferor/{orderNo}/{transferor}", method = RequestMethod.POST)
    public ResponseData transferor(@PathVariable("orderNo") long orderNo, @PathVariable("transferor") String transferor,
                                   Model model) throws Exception {
        logger.info("transferor p ==" + orderNo);
        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderNo);
        // 订单不存在
        if (orderInfo == null) {
            return new ErrorResponseData(-100, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
            //outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            return new ErrorResponseData(-100, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            return new ErrorResponseData(-100, "支付成功！请返回充值界面查看到账");

        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            return new ErrorResponseData(-100, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        orderInfo.setAliUserId(transferor);
        orderInfoService.updateTOrderInfo(orderInfo);
        return new SuccessResponseData();

    }


    //支付宝授权回调
    @RequestMapping(method = {RequestMethod.POST, RequestMethod.GET}, value = "common/aliPayTestAuth/{serviceName}/{orderCode}")
    public String aliPayAuthTest(HttpServletRequest request, @PathVariable(value = "orderCode") String orderCode, @PathVariable(value = "serviceName") String serviceName,
                                 @RequestParam(value = "auth_code", required = false) String auth_code,
                                 HttpServletResponse response, Model model) throws Exception {
        logger.info("接收加密后的订单号:" + orderCode);
        String content = AesEncryptUtils.decrypt(orderCode);

        Map<String, String> map = JSON.parseObject(content, Map.class);
        long recipientId = Long.valueOf(map.get("o"));
        long money = Long.valueOf(map.get("m"));
        long uid = Long.valueOf(map.get("u"));
        String nginxPayGateway = sysConfigService.selectConfigByKey("sys.bussine.nginxPayGateway");
        String callBackIpAddress = sysConfigService.selectConfigByKey("sys.bussine.callBackIpAddress");
        String notifyurl = callBackIpAddress + "";

        String returnurl = callBackIpAddress + "";

        String aliPrivateKey = sysConfigService.selectConfigByKey("sys.bussine.aliPrivateKey");
        String aliPublicKey = sysConfigService.selectConfigByKey("sys.bussine.aliPublicKey");
        String aliAppid = sysConfigService.selectConfigByKey("sys.bussine.aliAppid");
        String aliUserId = "";
        if (StringUtils.isEmpty(auth_code)) {
            String result = this.aliAuthUrl.replaceAll("0X99", aliAppid) + URLEncoder.encode(nginxPayGateway + GlobalConstants.API_BASE_URL + "common/aliPayTestAuth/" + serviceName + "/" + orderCode);
            logger.info("获取用户ID====" + result);
            String url = "<script>window.location.href=\"" + result + "\"</script>";
            try {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().println(url);
                response.getWriter().flush();
                response.getWriter().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            logger.info("auth_code====" + auth_code);
            AlipayClient alipayClient = null;
            alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliAppid, aliPrivateKey, "json", "GBK", aliPublicKey, "RSA2");


            AlipaySystemOauthTokenRequest alipaySystemOauthTokenRequest = new AlipaySystemOauthTokenRequest();
            // 值为authorization_code时，代表用code换取
            alipaySystemOauthTokenRequest.setGrantType("authorization_code");
            //授权码，用户对应用授权后得到的
            alipaySystemOauthTokenRequest.setCode(auth_code);
            //这里使用execute方法
            AlipaySystemOauthTokenResponse alipaySystemOauthTokenResponse = alipayClient.execute(alipaySystemOauthTokenRequest);
            //刷新令牌，上次换取访问令牌时得到。见出参的refresh_token字段
            alipaySystemOauthTokenRequest.setRefreshToken(alipaySystemOauthTokenResponse.getAccessToken());
            //返回成功时 就将唯一标识返回
            logger.info("返回====" + JSON.toJSONString(alipaySystemOauthTokenResponse));
            if (alipaySystemOauthTokenResponse.isSuccess()) {
                aliUserId = alipaySystemOauthTokenResponse.getUserId();
            }
            String queryAliBackUrl = sysConfigService.selectConfigByKey("sys.bussine.queryAliBackUrl");

            String aliBlackRs = HttpUtils.sendPostRequest(queryAliBackUrl + "/" + aliUserId, "");
            JSONObject aliBlackObj = JSONObject.parseObject(aliBlackRs);
            logger.info("查询专投库返回：" + aliBlackRs);
            if (aliBlackObj.getString("isBlack").equals("true")) {
                outPut(response, "aliObj获取订单失败！");
            }
            TRecipientInfo recipientInfo = recipientInfoService.selectTRecipientInfoById(recipientId);
            SysUser testUser = sysUserService.selectUserById(uid);
            //请求测试
            long nowTime = System.currentTimeMillis();
            Map<String, String> paramMap4Sign = new HashMap<>();
            paramMap4Sign.put("uid", String.valueOf(uid));
            paramMap4Sign.put("timestamp", String.valueOf(nowTime));
            paramMap4Sign.put("channel", recipientInfo.getChannel());
            paramMap4Sign.put("channelType", recipientInfo.getChannelType());
            paramMap4Sign.put("money", money + "");
            paramMap4Sign.put("goodsName", "测试商品");
            paramMap4Sign.put("notifyUrl", notifyurl);
            paramMap4Sign.put("returnUrl", returnurl);
            paramMap4Sign.put("outTradeNo", "app" + nowTime);
            paramMap4Sign.put("outUserId", "app");
            paramMap4Sign.put("aliAuthCode", auth_code);
            paramMap4Sign.put("aliUserId", aliUserId);
            paramMap4Sign.put("recipientId", recipientId + "");
            String signStr = MD5Util.stringMD5(SignUtil.formatUrlMap(paramMap4Sign, false) + "&key=" + testUser.getToken());
            paramMap4Sign.put("sign", signStr);
            StringBuilder buffer = new StringBuilder();
            SignUtil.buildPayParamsObj(buffer, paramMap4Sign);
            String url = nginxPayGateway + GlobalConstants.API_BASE_URL + "charges";
            String resultJson = HttpUtils.sendPostRequest(url, buffer.toString(), new HashMap<>());
            logger.info("url == {},demo下单结果：{}", url, resultJson);
            JSONObject rsObj = JSONObject.parseObject(resultJson);
            if (!rsObj.getString("code").equals("200")) {
                outPut(response, "通道异常,请再次重试！");
            }
            logger.info("测试获取的支付链接：" + rsObj.getJSONObject("data").getString("qrcodeUrl"));
            if (recipientInfo.getChannel().equals("alipay_wl_h5")) {
                model.addAttribute("payUrl", rsObj.getJSONObject("data").getString("qrcodeUrl"));
                return PATH_PREFIX + "openLink.html";
            } else if (recipientInfo.getChannel().equals("alipay_hdf_h5")) {
                model.addAttribute("tradeNo", rsObj.getJSONObject("data").getString("qrcodeUrl"));
                return PATH_PREFIX + "alipayByTradeNoPay.html";
            } else if (recipientInfo.getChannel().equals("alipay_eft_h5")) {
                model.addAttribute("tradeNo", rsObj.getJSONObject("data").getString("qrcodeUrl"));
                return PATH_PREFIX + "alipayByTradeNoPay.html";
            } else if (recipientInfo.getChannel().equals("alipay_cxzf_h5")) {
                model.addAttribute("tradeNo", rsObj.getJSONObject("data").getString("qrcodeUrl"));
                return PATH_PREFIX + "alipayByTradeNoPay.html";
            } else if (recipientInfo.getChannel().equals("alipay_cez_h5")) {
                String qrcode = rsObj.getJSONObject("data").getString("qrcodeUrl");
                JSONObject payInfo = JSONObject.parseObject(qrcode);
                model.addAttribute("payUrl", payInfo.getString("payInfo"));
                return PATH_PREFIX + "alipayByTradeNoInfoPay.html";

            }

        }
        return null;

    }


    @RequestMapping(value = "testPay", method = RequestMethod.GET)
    public String testPay(HttpServletRequest request, HttpServletResponse response,
                          Model model) throws Exception {
        return PATH_PREFIX + "test.html";
    }

    @RequestMapping(value = "isvAuth/{id}", method = {RequestMethod.POST, RequestMethod.GET})
    public void isvAuth(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "id") Long
            id, @RequestParam(value = "app_auth_code", required = false) String code) throws Exception {
        TRecipientInfo recipientInfo = recipientInfoService.selectTRecipientInfoById(id);
        String accountJson = recipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        // 填写您的APPID
        String appId = recipientInfo.getChannelAccount();

        String alipay_cert_path = accountObj.getString("alipay_cert_path").toString().replace("/home/product/product/deploy/resources/", "/root/alipayKey/");
        String alipay_public_cert_path = accountObj.getString("alipay_public_cert_path").toString().replace("/home/product/product/deploy/resources/", "/root/alipayKey/");
        String alipay_root_cert_path = accountObj.getString("alipay_root_cert_path").toString().replace("/home/product/product/deploy/resources/", "/root/alipayKey/");
        // 填写RSA2(SHA256)密钥 格式："应用私钥字符串"
        String privateKey = accountObj.getString("aliPrivateKey");

        // 支付宝网关
        String gateway = "https://openapi.alipay.com/gateway.do";

        // 创建API对应的客户端
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        //设置应用Id
        certAlipayRequest.setAppId(appId);
        //设置应用私钥
        certAlipayRequest.setPrivateKey(privateKey);
        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset("UTF-8");
        //设置签名类型
        certAlipayRequest.setSignType("RSA2");
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(alipay_cert_path);
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(alipay_public_cert_path);
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(alipay_root_cert_path);
        //构造client
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        // 设置授权grant_type，code模式通常为authorization_code
        String grantType = "authorization_code";
        // 创建API请求对象
        AlipaySystemOauthTokenRequest alipaySystemOauthTokenRequest = new AlipaySystemOauthTokenRequest();
        alipaySystemOauthTokenRequest.setGrantType(grantType);
        alipaySystemOauthTokenRequest.setCode(code);
        alipaySystemOauthTokenRequest.setRefreshToken("");
//        JSONObject bizContent = new JSONObject();
//        // 授权方式为通过授权码授权
//        bizContent.put("grant_type","authorization_code");
//        bizContent.put("code",code);
//        AlipayOpenAuthTokenAppRequest alipayOpenAuthTokenAppRequest = new AlipayOpenAuthTokenAppRequest();
//        alipayOpenAuthTokenAppRequest.setBizContent(bizContent.toString());
//        AlipayOpenAuthTokenAppResponse alipayOpenAuthTokenAppResponse = alipayClient.execute(alipayOpenAuthTokenAppRequest);
//        // 发送请求并获取响应
        AlipaySystemOauthTokenResponse alipaySystemOauthTokenResponse = alipayClient.execute(alipaySystemOauthTokenRequest);

        if (alipaySystemOauthTokenResponse.isSuccess()) {
            // 获取访问令牌
            String accessToken = alipaySystemOauthTokenResponse.getAccessToken();
            // 获取过期时间
            String expiresIn = alipaySystemOauthTokenResponse.getExpiresIn();
            // 获取刷新令牌
            String reFreshToken = alipaySystemOauthTokenResponse.getRefreshToken();
            // 获取用户ID
            String userId = alipaySystemOauthTokenResponse.getUserId();
            accountObj.put("accessToken", accessToken);
            recipientInfo.setAccountJson(JSONObject.toJSONString(accountObj));
            recipientInfo.setAlipayCardid(userId);
            recipientInfoService.updateTRecipientInfo(recipientInfo);
        }
    }


    @RequestMapping(value = "isvalipayzftPay", method = RequestMethod.GET)
    public String isvalipayzftPayPage(HttpServletRequest request, HttpServletResponse response,
                                      @RequestParam("p") String param,
                                      Model model) throws Exception {
        logger.info("fslsPay p ==" + param);
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";
        String nginxPayGateway = sysConfigService.selectConfigByKey("sys.bussine.nginxPayGateway");
        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(param);

        Map<String, String> map = JSON.parseObject(content, Map.class);
        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        // 订单支付超时
        if (orderInfo.getStatus() == OrderStatus.TIMEOUT.getCode()) {
            outPut(response, ServerExceptionEnum.PAY_TIMEOUT_ERROR.getMessage());
        }
        // 订单支付成功
        if (orderInfo.getStatus() == OrderStatus.PAY_SUCC.getCode()) {
            outPut(response, "支付成功！请返回充值界面查看到账。");
        }
        if (orderInfo.getStatus() != OrderStatus.WAIT_PAY.getCode()) {
            outPut(response, ServerExceptionEnum.ORDER_STATUS_ERROR.getMessage());
        }
        checkOK = true;

        if (checkOK) {
            TRecipientInfo tRecipientInfo = recipientInfoService.selectTRecipientInfoById(orderInfo.getRecipientId());
            TIsvInfo isvInfo = itIsvInfoService.selectTIsvInfoById(Long.valueOf(tRecipientInfo.getAlipayCardid()));
            TAliZftMerchantInfo aliZftMerchantInfo = new TAliZftMerchantInfo();
            aliZftMerchantInfo.setStatus(1);
            aliZftMerchantInfo.setIsvId(isvInfo.getId().toString());
            List<TAliZftMerchantInfo> aliZftMerchantInfoList = aliZftMerchantInfoService.selectTAliZftMerchantInfoListByNoAuth(aliZftMerchantInfo);
            AlipayClient alipayClient = getAliConfig(isvInfo);
            String channelAccount = "";
            AlipayTradeMergePrecreateRequest alipayTradeMergePrecreateRequest = new AlipayTradeMergePrecreateRequest();
            alipayTradeMergePrecreateRequest.setNotifyUrl(nginxPayGateway + "/notify/alizft/" + orderId);
            alipayTradeMergePrecreateRequest.setReturnUrl("");
            JSONObject bizContent = new JSONObject();
            TMergeOrderDetail mergeOrderDetail = new TMergeOrderDetail();
            String out_merge_no = "MERGE" + RandomUtil.randomNumbers(16);
            bizContent.put("out_merge_no", out_merge_no);
            mergeOrderDetail.setMergeNo(out_merge_no);
            mergeOrderDetail.setOrderId(String.valueOf(orderId));
            bizContent.put("timeout_express", "10m");
            JSONArray orderDetails = new JSONArray();
            JSONObject order1 = new JSONObject();
            order1.put("app_id", isvInfo.getIsvAppId());
            String out_trade_no = UUID.getOrder();
            order1.put("out_trade_no", "SUB_" + out_trade_no);
            mergeOrderDetail.setOutTradeNo("SUB_" + out_trade_no);
            mergeOrderDetail.setIsvId(isvInfo.getId().toString());
            SysDictData sysDictDataQuery = new SysDictData();
            sysDictDataQuery.setDictType("zft_subject");
            List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(sysDictDataQuery);
            Random random = new Random();
            int index = random.nextInt(sysDictDataList.size());
            SysDictData element = sysDictDataList.get(index);
            int moneyindex = random.nextInt(100) + 1;
            mergeOrderDetail.setPayRate(moneyindex);
            BigDecimal money1 = new BigDecimal(moneyindex * orderInfo.getMoney()).divide(new BigDecimal(100)).divide(new BigDecimal(100)).setScale(2);
            order1.put("subject", element.getDictLabel().replace("0x99amount", String.valueOf(money1)));

            order1.put("total_amount", money1);
            order1.put("product_code", "QUICK_WAP_WAY");
            // 结算信息，按需传入
            JSONObject settleInfo1 = new JSONObject();
            JSONArray settleDetailInfos1 = new JSONArray();
            JSONObject settleDetail1 = new JSONObject();
            settleDetail1.put("trans_in_type", "defaultSettle");
            settleDetail1.put("amount", money1);
            settleDetailInfos1.add(settleDetail1);
            settleInfo1.put("settle_detail_infos", settleDetailInfos1);
            order1.put("settle_info", settleInfo1);
            // 二级商户信息，按需传入
            JSONObject subMerchant1 = new JSONObject();
            index = random.nextInt(aliZftMerchantInfoList.size());
            aliZftMerchantInfo = aliZftMerchantInfoList.get(index);
            channelAccount += aliZftMerchantInfo.getAliasName();
            mergeOrderDetail.setSubMerId(aliZftMerchantInfo.getId().toString());
            mergeOrderDetail.setSubMerName(aliZftMerchantInfo.getAliasName());
            mergeOrderDetail.setStatus("WAIT_BUYER_PAY");
            mergeOrderDetail.setCreateUser(orderInfo.getUserId());
            subMerchant1.put("merchant_id", aliZftMerchantInfo.getSmid());
            order1.put("sub_merchant", subMerchant1);
            orderDetails.add(order1);
            itMergeOrderDetailService.insertTMergeOrderDetail(mergeOrderDetail);


            JSONObject order2 = new JSONObject();
            order2.put("app_id", isvInfo.getIsvAppId());
            out_trade_no = UUID.getOrder();
            order2.put("out_trade_no", "SUB_" + out_trade_no);
            mergeOrderDetail.setOutTradeNo("SUB_" + out_trade_no);
            index = random.nextInt(sysDictDataList.size());
            element = sysDictDataList.get(index);
            BigDecimal money2 = new BigDecimal(orderInfo.getMoney()).divide(new BigDecimal(100)).subtract(money1).setScale(2);
            order2.put("subject", element.getDictLabel().replace("0x99amount", money2.toString()));
            order2.put("total_amount", money2);
            order2.put("product_code", "QUICK_WAP_WAY");
            // 结算信息，按需传入
            JSONObject settleInfo2 = new JSONObject();
            JSONArray settleDetailInfos2 = new JSONArray();
            JSONObject settleDetail2 = new JSONObject();
            settleDetail2.put("trans_in_type", "defaultSettle");
            settleDetail2.put("amount", money2);
            settleDetailInfos2.add(settleDetail2);
            settleInfo2.put("settle_detail_infos", settleDetailInfos2);
            order2.put("settle_info", settleInfo2);
            // 二级商户信息，按需传入
            JSONObject subMerchant2 = new JSONObject();
            index = random.nextInt(aliZftMerchantInfoList.size());
            aliZftMerchantInfo = aliZftMerchantInfoList.get(index);
            channelAccount += "," + aliZftMerchantInfo.getAliasName();
            subMerchant2.put("merchant_id", aliZftMerchantInfo.getSmid());
            order2.put("sub_merchant", subMerchant2);
            mergeOrderDetail = new TMergeOrderDetail();
            mergeOrderDetail.setMergeNo(out_merge_no);
            mergeOrderDetail.setOrderId(String.valueOf(orderId));
            mergeOrderDetail.setOutTradeNo("SUB_" + out_trade_no);
            mergeOrderDetail.setIsvId(isvInfo.getId().toString());
            mergeOrderDetail.setPayRate(100 - moneyindex);
            mergeOrderDetail.setSubMerId(aliZftMerchantInfo.getId().toString());
            mergeOrderDetail.setSubMerName(aliZftMerchantInfo.getAliasName());
            mergeOrderDetail.setStatus("WAIT_BUYER_PAY");
            mergeOrderDetail.setCreateUser(orderInfo.getUserId());
            itMergeOrderDetailService.insertTMergeOrderDetail(mergeOrderDetail);
            orderDetails.add(order2);

            bizContent.put("order_details", orderDetails);
            orderInfo.setRecipientRealName(channelAccount);
            orderInfo.setAliUserId(isvInfo.getId().toString());
            orderInfoService.updateTOrderInfo(orderInfo);
            alipayTradeMergePrecreateRequest.setBizContent(bizContent.toString());
            logger.info("直付通请求参数 ==" + JSONObject.toJSON(alipayTradeMergePrecreateRequest));
            AlipayTradeMergePrecreateResponse alipayTradeMergePrecreateResponse = alipayClient.certificateExecute(alipayTradeMergePrecreateRequest);
            logger.info("alipayTradeMergePrecreateResponse ==" + JSONObject.toJSON(alipayTradeMergePrecreateResponse));
            if (alipayTradeMergePrecreateResponse.isSuccess()) {
                AlipayTradeWapMergePayRequest alipayTradeWapMergePayRequest = new AlipayTradeWapMergePayRequest();
                alipayTradeWapMergePayRequest.setBizContent("{" +
                        "\"pre_order_no\":\"" + alipayTradeMergePrecreateResponse.getPreOrderNo() + "\"" +
                        "  }");
                AlipayTradeWapMergePayResponse alipayTradeWapMergePayResponse = alipayClient.pageExecute(alipayTradeWapMergePayRequest);
                outPut(response, alipayTradeWapMergePayResponse.getBody());
            } else {
                logger.info("调用失败" + JSONObject.toJSON(alipayTradeMergePrecreateResponse));
                return view;
            }
        }
        return view;
    }

    private AlipayClient getAliConfig(TIsvInfo isvInfo) throws AlipayApiException {
        String appCertPath = isvInfo.getIsvAppPublicPath();//"/Users/mac/Documents/WORK/场景/直付通11/appCertPublicKey_2021003196668931.crt";
        // 支付宝公钥证书路径
        String alipayCertPath = isvInfo.getIsvAliPublicPath();//"/Users/mac/Documents/WORK/场景/直付通11/alipayCertPublicKey_RSA2.crt";
        // 支付宝根证书路径
        String alipayRootCertPath = isvInfo.getIsvAliRootPath();//"/Users/mac/Documents/WORK/场景/直付通11/alipayRootCert.crt";

        // 应用APPID
        String appId = isvInfo.getIsvAppId();//"2021003196668931";
        // 初始化SDK
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        //设置网关地址
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        //设置应用Id
        certAlipayRequest.setAppId(appId);
        //设置应用私钥
//        certAlipayRequest.setPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCYjCsmZsld84YkTStL/AATrGzCmSLb6J4FZGV4eYSZWdGhsPDf3XEzCMTL/g3WvDNIISGiVek2NYXGKqy6VMdKHoS+miypmJVZ3EkgPwj/0hJWeyrKvWFn1nIUeW8u7mnJ7KJl51Opaj/+RUtkGWHKxOrBCY5KT2q7hiUTszuLCt23muU8dF9nxL9Kc+x6NgtPhj/oGdJNgQZMdjBqvshZ06oVoHcWDzK+zJJmft4YI+Km1+Uvcyk5ZtPDFXaqeFuSCUPBdRHq9AdoUG/CW1Xy0xVcICAZnI0SzuhKH9eEhyuLQ8yKHp8kajzXTxCUgKU5qI8wQmI2YiupVdQ+HqhDAgMBAAECggEAUcxnnvHi7HQW7ARNQTNhvyroLvj6jj0P7whEuPNAPRLCrBc7Mm+Fsb3z+QbD2O+V+Al8BZZXtW/Byd88O7YWHxJ6T9JQPKjK/SJ4O8hRRQwaNTFaYthmEM4W4g+zpNDG/TXcZxRB8kg9BFWX9Zb+r0IkN1quZ/5p1yA5ZXToaseW53da2N7TESXvrEGj4wQ91iHbRKVkCQGJBOPWuxKvmwU8h1NzpvQ4c1O/ZTuOmYzdBpNOVmNh5po1UGOkBYAMudh04X1CNBiSMkhrORe7Pw3grrOSyARSfutvQthww/xQ4JqHpi353gCPXwl22PXjUBRwXRKvaZM43w7h85vC4QKBgQDHSGI3j8Fes+HNhb/PXTETG1e4BFH1XQJgGXICOe5f4+Yi7Ih5KJrUu5xpD95/lYHqfnkXJhAzKFhcnCN8/3pol9af1WZU74XPjVmhE5pm1NoBjxqTFiS4g74TsGrCr3meE7C0fHuEL50LEJ+gzUhynKqjbir/j2fzHw/BiLYOKwKBgQDD9q+1aMsZ4QA1Xohu9bXHP2rD7UZzvrqD06rjEFuKnRWcob5afADKwx/wvlMucARPHMGMy/4uoBlDE5cLVRcFgq0Id2JiO9JpBWLJBMeEWKpF5ql9fEjayRiunaSt0rMKc6jjVfZxOOGrSdGlhZfjT9kwJpkyGtu5RhrhwGzaSQKBgG0twemQz68TvBT+PtzbwKQoKcG+VCyp/UArEKQZmvhcAlyF3CsMzO7ZrlJ9CDg778ZJ7gt5pgxxASATxvmXejfNYB+HKZ5E77mLRlySQdguqxWJklSdIBcazks5LvRkcKvjO79WJ9F+yHokbGALt7JbFL2fAN2scpXnIZm1TZCrAoGBAKqIWpA8CcMTkuLeyUwGd5JVFcw7CDxhll5yLRw8d+1AljYga07C6s2I0Jroheq7gIR4OdcVDrX0jQdaXO93tPkOpxXfDrb96DWMglL83cPGhScffA+/wIbkyZ3rggvid/x4elibzkLphTlSnCa3A17FdfP5Iwf/Z4bsAyjCE/hBAoGAP3e6umlHA/YSvULwK8W+5+CSql8tfMcycn7+IzZb8x4E5mwMERyViUBPTtLD+96HpLvNgiCtGTi+N0i0xa3mxyrOJwIvnKawCrHjO44wrtW59XLD6Ns8J2VxW9BYuGNFJ7SU+PXJ5nVNhdC9USLs9B7agLOJ9mOmNWCRuW1Jvrs=");
        certAlipayRequest.setPrivateKey(isvInfo.getIsvAliPrivateKey());

        //设置请求格式，固定值json
        certAlipayRequest.setFormat("json");
        //设置字符集
        certAlipayRequest.setCharset("UTF-8");
        //设置签名类型
        certAlipayRequest.setSignType("RSA2");
        //设置应用公钥证书路径
        certAlipayRequest.setCertPath(appCertPath);
        //设置支付宝公钥证书路径
        certAlipayRequest.setAlipayPublicCertPath(alipayCertPath);
        //设置支付宝根证书路径
        certAlipayRequest.setRootCertPath(alipayRootCertPath);
        //构造client
        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        return alipayClient;
    }


    @RequestMapping(value = "/upOrder", method = RequestMethod.POST)
    @ResponseBody

    public ResponseData upOrder(UpOrderReq upOrderReq, HttpServletRequest request) throws Exception {
        logger.info("sybPay p ==" + upOrderReq.getOrderId());
        Map<String, Object> retMap = new HashMap<>();
        retMap.put("data", null);
        retMap.put("ret", false);
        String view = "error";

        boolean checkOK = false;
        //参数解密
        String content = AesEncryptUtils.decrypt(upOrderReq.getOrderId());

        Map<String, String> map = JSON.parseObject(content, Map.class);
        long orderId = Long.valueOf(map.get("o"));
        String channel = map.get("c");


        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(orderId);
        // 订单不存在
        if (orderInfo == null) {
//            outPut(response, ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
            return new ErrorResponseData(ServerExceptionEnum.NOTEXIST_ORDER.getMessage());
        }
        TRecipientInfo tRecipientInfo = recipientInfoService.selectTRecipientInfoById(orderInfo.getRecipientId());

        orderInfo.setAliAuthCode(upOrderReq.getName());
        orderInfoService.updateTOrderInfo(orderInfo);
        //同步
        TPayChannel payChannel = payChannelService.selectTPayChannelByCode(channel);
        String paramInfo = payChannel.getParamInfo();
        JSONObject paramObj =   JSONObject.parseObject(paramInfo);
        String syncUrl = paramObj.getString("syncUrl");
        JSONObject reqObj = new JSONObject();
        StringBuffer syncInfo = new StringBuffer("<strong>您有一笔新的充值订单,请及时处理</strong>\n订单号："+orderId+"\n账户类型：支付宝\n收款人："+tRecipientInfo.getRealName()+"\n收款账号："+tRecipientInfo.getChannelAccount());
        syncInfo.append("\n---------------------------------------------------\n付款人姓名："+upOrderReq.getName()+"\n付款金额："+MoneyUtil.fenToYuan(orderInfo.getMoney()+"")+"元\n---------------------------------------------------\n请及时确认！！！");
        reqObj.put("syncInfo",syncInfo);
        logger.info("发送机器人同步订单消息网关：{},参数：{}",syncUrl.replace("0x99merOrder",orderInfo.getOutTradeNo()),syncInfo.toString());
        String payRes = HttpUtils.sendJsonMessage(syncUrl.replace("0x99merOrder",orderInfo.getOutTradeNo()), new HashMap<>(), reqObj.toJSONString());
        return new SuccessResponseData();
    }

    @RequestMapping(value = "/alipayzhzz", method = RequestMethod.GET)
    public String alipayzhzz(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam("p") Long param,
                              Model model) throws Exception {
        TOrderInfo orderInfo = orderInfoService.selectTOrderInfoById(param);
        String payUrl = "alipays://platformapi/startapp?appId=09999988&actionType=toAccount&amount="+ MoneyUtil.fenToYuan(orderInfo.getMoney()+"")+"&memo="+orderInfo.getId();
        model.addAttribute("payUrl", payUrl);
        return PATH_PREFIX + "alipayByZhzzPay.html";
    }

}
